Issue
Image I have 2 buttons, A and B. I have a function, called mystery(). Both buttons A and B, when pressed, will activate mystery(), but if button A is pressed, mystery() somehow knows it was button A that activated it, and if button B is pressed, mystery() somehow knows it was button B that activated it. If it was button A that activated mystery(), mystery() will stop the app, but if it was button B that activated mystery(), mystery will give the player 100 dollars.
That was just a random example, but basically what I'm asking is: is there a way to pass what button triggered a function? I get I could have two functions, mysteryA and mysteryB, where the former is linked to A and the latter is linked to B, and just copy and paste and have slight variations in each one, but there must be a more efficient way to do this.
Any thoughts?
Solution
yes, it's possible (here's a java example)
public class abc extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
}
public void myMethod(View view) {
//here, you can use something like view.getId() or anything else to identify which view called this method
//you could do something like this :
if (view.getId() == R.id.button2) {
giveALocalNobody100Dollars();
}else if (view.getId() == R.id.button3){
giveItToHimEitherWayHeDeservesIt();
}
}
}
and your xml :
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:onClick="myMethod"/>
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button3"
android:onClick="myMethod"/>
now, in your onClickListener, myMethod
you have access to a view
, and with this view you can determine which button called it
Answered By - a_local_nobody
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.