Simultaneous pressing of multiple buttons not detected

I have to catch android project if two buttons are pressed or not. I have created OnTouchListener

and implemented onTouch()

. However, only the first button pressed is detected when I press two buttons at the same time.

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.game_layout);

    mShootButton = (Button) findViewById(R.id.btn_shoot);
    mAccelerateButton = (Button) findViewById(R.id.btn_accelarate);

    MyTouchListener touchlistener = new MyTouchListener();
    MyTouchListener touchlistener2 = new MyTouchListener();
    mShootButton.setOnTouchListener(touchlistener);
    mAccelerateButton.setOnTouchListener(touchlistener2);
    super.onCreate(savedInstanceState);
}

public class MyTouchListener implements OnTouchListener {
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN && v.getId() == R.id.btn_shoot){
            setmShootButtonPressed(true);
        }
        else if(event.getAction() == MotionEvent.ACTION_UP && v.getId() == R.id.btn_shoot){
            setmShootButtonPressed(false);
        }

        if(event.getAction() == MotionEvent.ACTION_DOWN && v.getId() == R.id.btn_accelarate){
            setmAccelerateButtonPressed(true);
        }
        else if(event.getAction() == MotionEvent.ACTION_UP && v.getId() == R.id.btn_accelarate){
            setmAccelerateButtonPressed(false);
        }
        return true;
    }
}

      

NB: My phone is multitouch, I checked.

+3


source to share


1 answer


Try it android:splitMotionEvents="true"

on a layout containing buttons.

Explanation: Android buttons are not designed to be used concurrently. One of them will consume the touch event and the layout container will not raise the onTouch event of the other button.



Alternatively, you can create a custom view that handles the click detection logic for both buttons.

See: Android multitouch button

+2


source







All Articles