When inflating a layout xml dynamically multiple times, how can I differentiate or identify the Button widgets?

前端 未结 3 1323
庸人自扰
庸人自扰 2021-01-18 00:36

I am inflating an xml having button, multiple times and i am able to do so perfectly but the problem is when I click the button,i want to show which button is clicked.

3条回答
  •  灰色年华
    2021-01-18 01:09

    You can use setTag() to each button. Inside the for loop you can assign button.setTag(). And you can use getTag() to retrieve button's tag. After you inflate the layout, add a tag to your button

    EDIT2: You should inflate the layout and then look up for your button id. See below:

        public class InflateExActivity extends Activity {
                /** Called when the activity is first created. */
                @Override
                public void onCreate(Bundle savedInstanceState) {
                    LinearLayout lLayout;
                    final Button b = null;
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    for(int i=0;i<3;i++){
                        final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.buttons, null);
    b = v.findViewById(R.id.your_button_id);
        //                 b = (Button) inflater.inflate(R.layout.buttons, null);
                           b.setTag(i); // you'll get 0,1,2 as tags
                        lLayout = (LinearLayout) findViewById(R.id.layout1);
                        lLayout.addView(b);
                        b.setOnClickListener(new OnClickListener() {
    
                            public void onClick(View v) {
        int specificButton = (Integer)v.getTag();//Changed here.......
                                Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton),
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }  
            }
    

提交回复
热议问题