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

核心思路是通过多点触控获取的按压状态,将所有想要被触发按压的按钮放到数组里,最后将所有按压状态映射到一个整形 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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值