How to add a button dynamically in Android?

后端 未结 17 1143
礼貌的吻别
礼貌的吻别 2020-11-22 13:17

How to add a button dynamically in Android?

17条回答
  •  太阳男子
    2020-11-22 13:30

    try this:

    for (int i = 1; i <= 20; i++) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        Button btn = new Button(this);
        btn.setId(i);
        final int id_ = btn.getId();
        btn.setText("button " + id_);
        btn.setBackgroundColor(Color.rgb(70, 80, 90));
        linear.addView(btn, params);
        btn1 = ((Button) findViewById(id_));
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(view.getContext(),
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }
    

提交回复
热议问题