3

I must catch in an android project, if two buttons are pressed or not. I have created an OnTouchListener and implemented onTouch(). However, only the first pressed button is detected, when I press two buttons at 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;
    }
}

N.B.: My phone is multitouch, I've checked.

ci_
  • 8,594
  • 10
  • 39
  • 63
Osaky11
  • 73
  • 1
  • 1
  • 4
  • If you are making a game (as it appears you are), you probably want to move away from button controls and go to something like Cocos2D (http://www.cocos2d-x.org) which has gamepad controls and multitouch support. – David S. May 11 '15 at 14:18

1 Answers1

2

Try android:splitMotionEvents="true" on the layout that contains the buttons.

Explaination: Android buttons are not designed to be touched at the same time. One of them will consume the touch event and the layout container will not call the onTouch event of the other button.

As an alternative you could create a custom view that handles the click detection logic for both buttons.

See: Android work multitouch button

Community
  • 1
  • 1
davidgiga1993
  • 2,695
  • 18
  • 30