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

发布于 2021-01-29 19:37:47

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

关注者
1
被浏览
1129
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    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);
    


  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看