Reputation: 1003
I have an app with a lot of buttons (more than 300) i want to know if there is a way to use android:onClick="function" with an arguments in my layout xml because im too lazy to make a function for each button, and i want to do somenthin like
public void allbuttons(View view, String stringa) {
if stringa = 1 { bla bla bla}
elif stringa = 2 { blachos}
}
you get the idea
Upvotes: 1
Views: 1381
Reputation: 2006
Give an id to each of your button. In your common handler, just check the ((Button)view).getId() for the id in a switch (with the latest adk, you have to use if-else) and handle it differently in each case.
public class MyButtonClickHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
Button button = (Button) v;
if (button.getId() == R.id.button1) {
Toast.makeText(Sample1Activity.this, "Toast1", 1000).show();
} else if (button.getId() == R.id.button2) {
Toast.makeText(Sample1Activity.this, "Toast2", 1000).show();
}
}
}
and in your onCreate of activities you can add
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new MyButtonClickHandler());
I am adding function reference in the code but you can do it in xml file too.
Upvotes: 3