Issue
public class TwoPlayers extends AppCompatActivity implements
View.OnClickListener {
private Button start, start2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two_players);
start = (Button) findViewById(R.id.buttonStart);
start2 = (Button) findViewById(R.id.buttonStrat2);
start.setOnClickListener(this);
start2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if((v == start)&&(v == start2)){
start.setVisibility(View.GONE);
start2.setVisibility(View.GONE);
...
Initially I thought this will be very easy to do since all phones support multi-touch for years now, but now that I red around it seems it's harder to do than I tought, I need to press 2 buttons simultaneously to start a game. My approach with onClick listener above doesn't work. What will be the easiest way to do this ? Because the approach I found so far involves using OnTouchListener and ACTION_DOWN, and then record some coordinates, and check if the coordinates are within button area, which is kind of complex. Not only that but all my other buttons are using onClick and if I use just for starting the game onTouch will I have to use it for all the other buttons as well or I can leave them using onClick ?
Solution
The condition if((v == start)&&(v == start2))
can never be true. v
cannot have two different values at the same time.
The onClick method will be called twice, one time when you press the start
button and another time when you press the start2
button.
You can use the isPressed method to check when the views are pressed at the same time (Button
is a View
, so it inherits all its methods).
In other words:
@Override
public void onClick(View v) {
if(start.isPressed() && start2.isPressed()) {
start.setVisibility(View.GONE);
start2.setVisibility(View.GONE);
...
When the first button is pressed, onClick is called but the condition is false. When the second button is pressed (and the first one is still pressed) the condition will be true.
Answered By - jmart
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.