1

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

tiranodev
  • 943
  • 2
  • 8
  • 15
  • check out this answer: http://stackoverflow.com/questions/4153517/how-exactly-does-the-androidonclick-xml-attribute-differ-from-setonclicklistene – Phobos Nov 27 '11 at 06:56

1 Answers1

3

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.

bschandramohan
  • 1,968
  • 5
  • 27
  • 52
  • thanks :) i need to add this to each activity class or make 1 class for this? – tiranodev Nov 27 '11 at 07:22
  • 2
    MyButtonClickHandler is a public class and in a separate file by itself. The Click Listener has to be added to each button in the Activity java file OR in the Activity's XML file. – bschandramohan Nov 29 '11 at 04:15
  • 1
    thank you :P i used public void onClick(View v) and switch/case statements for this thank you for the basic idea :) – tiranodev Nov 29 '11 at 04:30