I want to do something, where I will have 4 buttons. There will only be a success if 2 matching buttons are pressed. At the moment I only know how to handle one button click, but I don’t know how to make it so that if I press a button, and then afterwards press another button.. a fail or success occurs depending on the button pressed.
What would I use to go on about implementing this?
If you mean that you want to detect simultaneous press of two buttons, you can set an
OnTouchListenerfor the buttons and detect when each one is pressed or released. With a little bookkeeping, you can then detect whether the user presses two matching buttons at the same time.If you want to track successive button clicks, then you need some way of identifying which button was last clicked. There are a couple of ways to do this. One is to assign a different
OnClickHandler(or a differentandroid:onClickmethod) to each button. Another way (better, in my opinion) is to assign a unique tag value to each button. In XML, the tag will be a string, which you can then parse into an int value usingInteger.parseInt(); in code it can be an Integer. Then your click handler determines the button’s tag value and uses that in the program logic.The way you would use this is as follows. Define a field in your game class for the last button clicked. Before any buttons are clicked, it should have the value -1 (indicating no button). Then when you get a button click, determine its identity (either from the tag or by which click handler was invoked). Check whether the last button and the current button form a correct sequence. If not, then set the last button to the current button.