0
点赞
收藏
分享

微信扫一扫

安卓开发中解决多点触控触发多个按钮的问题

GG_lyf 2022-05-23 阅读 45


核心思路是通过多点触控获取的按压状态,将所有想要被触发按压的按钮放到数组里,最后将所有按压状态映射到一个整形 ​​buttonMask​​ 上。


一个整形为32位,足够映射32个按钮,对一般需求是绝对满足了。如果还不够可以用​​long​​。


示例代码如下:

@Override
public boolean onTouchEvent(MotionEvent event) {
final int BUTTONS_COUNT = 10;
View[] buttons = new View[BUTTONS_COUNT];

// 此处将所有按钮放到数组里
// buttons[0] = findViewById(R.id.hello_text_view);
// buttons[1] = findViewById(R.id.hello_text_view2);

int pointerCount = event.getPointerCount();
int actionMasked = event.getActionMasked();
int pointerIndex = event.getActionIndex();

int buttonMask = 0;

for (int i = 0; i < pointerCount; ++i) {
int touchX = (int)event.getX(i);
int touchY = (int)event.getY(i);
boolean buttonPressed = false;

if (pointerIndex == i) {
if (actionMasked == MotionEvent.ACTION_MOVE || actionMasked == MotionEvent.ACTION_DOWN) {
buttonPressed = true;
}
} else {
buttonPressed = true;
}

if (!buttonPressed) {
continue;
}

for (int buttonIndex = 0; buttonIndex < mButtons.length; ++buttonIndex) {
Rect buttonRect = new Rect();
View button = buttons[buttonIndex];
int[] location = new int[2];
button.getLocationInWindow(location);
buttonRect.left = location[0];
buttonRect.top = location[1];
buttonRect.right = location[0] + button.getWidth();
buttonRect.bottom = location[1] + button.getHeight();
if (buttonRect.contains(touchX, touchY)) {
buttonMask |= (1 << buttonIndex);
break;
}
}
}

android.util.Log.v("test", String.format("mask = %x", buttonMask));

return super.onTouchEvent(event);
}



举报

相关推荐

0 条评论