现在的位置: 首页 > 综合 > 正文

Android中如何模拟一次点击(touch)事件

2013年03月14日 ⁄ 综合 ⁄ 共 602字 ⁄ 字号 评论关闭

    在Android中有时需要模拟某一个View的touch事件,来达到对该View的功能相应处理的简单化,因为你只需要模拟对该View的touch事件,便能沿着原来touch的事件相应走下去,不需要添加任何代码,你可以这么做:

final long downTime = SystemClock.uptimeMillis();
final MotionEvent downEvent = MotionEvent.obtain(
        downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0);
final MotionEvent upEvent = MotionEvent.obtain(
        downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x, y, 0);

mSeekBar.onTouchEvent(downEvent);
mSeekBar.onTouchEvent(upEvent);

downEvent.recycle();
upEvent.recycle();

    从代码可以看出这里的重点是需要知道两个点:一是你模拟点击的坐标,在这里就是xy,二就是你需要设置响应这个点击事件的View,这里是一个SeekBar,这个点击的坐标一般也选在这个需要响应View上,我的使用场景是在遥控器的确定键的相应上,如果还有新的应用场景,请多交流哦。

抱歉!评论已关闭.