Question

I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?

Was it helpful?

Solution

You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..

Update: code could be soemthing along these lines:

View.OnClickListener getOnClickDoSomething(final Button button)  {
    return new View.OnClickListener() {
        public void onClick(View v) {
            button.setText("text now set.. ");    
        }
    };
}

as a method in the activity and then use it in the loop like this

button.setOnClickListener(getOnClickDoSomething(button));

OTHER TIPS

I got one solution for this.. use this code in onCreate

linear = (LinearLayout) findViewById(R.id.linear);

LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);

Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
    btn[i] = new Button(getApplicationContext());
    btn[i].setText(num_array_name[i].toString());
    btn[i].setTextColor(Color.parseColor("#000000"));
    btn[i].setTextSize(20);
    btn[i].setHeight(100);
    btn[i].setLayoutParams(param);
    btn[i].setPadding(15, 5, 15, 5);
    linear.addView(btn[i]);

    btn[i].setOnClickListener(handleOnClick(btn[i]));

}

after onCreate create one method of return type View.OnClickListener like this..

View.OnClickListener handleOnClick(final Button button) {
    return new View.OnClickListener() {
        public void onClick(View v) {
        }
    };
}
Button.OnClickListener btnclick = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Button button = (Button)v;
    Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();  
    }

};

call this listener by btn.setOnClickListener(btnclick);

View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.

Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().

instead use setTag() function to distinct easily.

 for(int i=0;i<4;i++) {
     Button btn = new Button(this);
     btn.setTag(i);
     btn.setOnClickListener(new View.OnclickListener() {
         @Override
         public void onClick(View v) {
             int i=v.getTag();
             switch(i) {
                 case 1: btn.setText(i);
                     break;

                 case 2: btn.setText(i);
                     break;

                 case 3: btn.setText(i);
                     break;

                 case 4: btn.setText(i);
                     break;

                 default: btn.setText("Others");
             }
         }
     }

"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.

I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.

Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout

This answer may you help: https://stackoverflow.com/a/5291891/2804001

public class MainActivity extends Activity implements View.OnClickListener
{

LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
    String[] array={"U123","U124","U125"};
    int length=array.length;
    System.out.println("11111111111111111111111111");
    button=new Button[length];
    for(int i=0;i<length;i++)
    {
        button[i]=new Button(getApplicationContext());
        button[i].setId(i);
        button[i].setText("User" + i);
        button[i].setOnClickListener(this);
        linearLayout.addView(button[i]);
    }
}
@Override
public void onClick(View view)
{
    view.getId();
    Button button=(Button)findViewById(view.getId());
    button.setText("Changed");
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top