Percy

如何在Android中动态添加按钮?

android

如何在Android中动态添加按钮?


阅读 361

收藏
2020-12-04

共2个答案

小编典典

Button myButton = new Button(this);
myButton.setText("Push Me");

LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
2020-12-04
小编典典

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();
        }
    });
}
2020-12-04