Android- React When 2 Button Clicked
Solution 1:
In xml, use the same name for your onClick
for each Button
<Button
android:id="@+id/btn1"
...
android:onClick="btnClick"/>
<Button
android:id="@+id/btn2"
...
android:onClick="btnClick"/>
And in your java code make sure that the function is public, has the same name you defined in your xml's onClick
property above, and that it takes a View
as its only parameter. The View
will be the Button
clicked so you can get its id
and switch
on that, use if/else
or however you want to handle that
publicvoidbtnClick(View v)
{
switch(v.getId()) // v is the btn that was clicked so this will give you its id
{
case (R.id.btn1): btn1 was clicked
... do stuff
To answer your first question, you can use a flag as suggested earlier or a counter and if the counter == say 2 then the click does whatever you need. If it doesn't then you store the value of what that Button
represents to compare in the second click
the other way would be to set them in a for loop
, I assume you know how to set up a loop
so I will keep this short
for (int i=0; i<buttons.size(); i++)
{
...
button[i].setOnClickListener(ActivityName.this);
}
@OverridepublicvoidonClick(View v)
{
intid= v.getId();
}
Make sure you implement OnClickListener()
Solution 2:
Using logic I was able to create a program, but it's very long. For each button you should do the same:
Button B1;
int x,y; //give them values and compare (example: B1=1, B2=2, B3=1 .. B1&B3 the same picture)intturn=1; //to know whos turn (x or y), default start on xint numberOfClicks=0; //when 2 buttons clicked, check//in the OnCreate()
B1 = (Button) findViewById(R.id.b1); //assume B1's value = 1
B1.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View arg0) { //------------------------------------ OnClick Starts hereif (turn==1){
//use x
x=1;
turn=2; //flip the turn
numberOfButtons++; //one is clicked so far
}else{
//use y
y=1;
turn=1;
numberOfButtons++;
}
if(numberOfButtons==2){
//checkif(x==y){
//same
numberOfButtons=0; //restart counter
}else{
//not the same
numberOfButtons=0; //restart counter
}
}//end of OnClick
}); //end of button OnClickListener
if B2=7, then in the OnClick, the x and y should = 7. Each OnClick will have different x and y values.
Post a Comment for "Android- React When 2 Button Clicked"