個(gè)人博客:haichenyi.com。感謝關(guān)注
??本篇介紹實(shí)現(xiàn)模擬點(diǎn)擊的兩種方式:
- performClick();
- MotionEvent事件
??舉個(gè)栗子:我們現(xiàn)在需要實(shí)現(xiàn)點(diǎn)擊A按鈕,觸發(fā)B按鈕點(diǎn)擊事件的效果:兩個(gè)按鈕在布局里面隨便創(chuàng)建就好了嚼松。
??第一種方式就是:調(diào)用performClick事件
Button btn1 = findViewById(R.id.btn1);
final Button btn2 = findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("wz","btn1");
btn2.performClick();
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("wz","btn2");
}
});
??這種方式很簡(jiǎn)單尖淘,但是有一個(gè)弊端颈将,就是不會(huì)傳遞觸摸點(diǎn)坐標(biāo)驹针,只是模擬一下btn2的點(diǎn)擊事件殖告。
??第二種方式就是:MotionEvent事件
Button btn1 = findViewById(R.id.btn1);
final Button btn2 = findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("wz","btn1");
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis()+100;
float upX = btn2.getX()+50;
float upY = btn2.getY()+50;
MotionEvent obtainDown = MotionEvent.obtain(downTime, eventTime, ACTION_DOWN, upX, upY, 0);
long downTime1 = SystemClock.uptimeMillis();
long eventTime1 = SystemClock.uptimeMillis()+100;
float upX1 = btn2.getX()+50;
float upY1 = btn2.getY()+50;
MotionEvent obtainUp = MotionEvent.obtain(downTime1, eventTime1, MotionEvent.ACTION_UP, upX1, upY1, 0);
btn2.dispatchTouchEvent(obtainDown);
btn2.dispatchTouchEvent(obtainUp);
obtainDown.recycle();
obtainUp.recycle();
Log.v("wz","downTime:"+downTime+" ,eventTime:"+eventTime+" ,upX:"+upX+" ,upY:"+upY+" ,downTime1:"+downTime1+" ,eventTime1:"+eventTime1+" ,upX1:"+upX1+" ,upY1:"+upY1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("wz","btn2");
}
});
??這種方式比較麻煩阿蝶,用到的就是view的事件分發(fā),一個(gè)簡(jiǎn)單的點(diǎn)擊事件的觸發(fā)就是down和up組成黄绩,當(dāng)然還有平移我們這里不考慮羡洁。
??第一步,先用MotionEvent.obtain創(chuàng)建兩個(gè)事件:一個(gè)down事件爽丹,一個(gè)up事件筑煮,創(chuàng)建的時(shí)候需要傳遞坐標(biāo)點(diǎn),傳你目標(biāo)view的范圍內(nèi)的坐標(biāo)就行习劫。
??第二步咆瘟,通過(guò)目標(biāo)view,也就是這里的btn2去把這兩個(gè)事件分發(fā)出去诽里,通過(guò)dispatchTouchEvent分發(fā)袒餐,這樣就完成了一次模擬點(diǎn)擊事件,分發(fā)完記得回收
??這樣谤狡,就完成了一次模擬點(diǎn)擊灸眼,并且坐標(biāo)也傳遞了。因?yàn)槟苟瑒?chuàng)建這兩個(gè)事件的時(shí)候就傳遞了焰宣。解決了performClick的弊端。