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

前端 未结 3 1212
庸人自扰
庸人自扰 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 00:55

    items you are adding programmatically, you must have to assign ids to them.

    b.setId(1);
    

    EDITED:

    public class DynamicLayoutActivity extends Activity implements OnClickListener{
    private static final int MY_BUTTON = 9000;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
    
        // add button
        Button b = new Button(this);
        b.setText("Button added dynamically!");
        b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,   LayoutParams.WRAP_CONTENT));
        b.setId(MY_BUTTON);
        b.setOnClickListener(this);
        ll.addView(b);
    }
     public void onClick(View v) {
            Toast toast;
            Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
            switch (v.getId()) {
            case MY_BUTTON:
                toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400);
                toast.show();    
            }
        }
    

    LATEST:

    public class InflateExActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            LinearLayout lLayout;
            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);
                 b = (Button) inflater.inflate(R.layout.buttons, null);
                 b.setId(i);
                lLayout = (LinearLayout) findViewById(R.id.layout1);
                lLayout.addView(b);
                b.setOnClickListener(new OnClickListener() {
    
                public void onClick(View v) {
                    Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(),
                            Toast.LENGTH_LONG).show();
                }
            });
        }
    }  
    

提交回复
热议问题