3

我想通过按钮单击代码动态添加多个按钮,我搜索了许多以前显示添加单个按钮的帖子,但我需要多个按钮。

附上示例代码。

   public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {      
            @Override
            public void onClick(View v) {               
                AddAll();                   
            }
        });
    }
    public void AddAll() {
        final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);
        final Button btn = new Button(this);
        for(int i=0;i<4;i++)
        {
            rl.addView(btn); 
            btn.setText("hello");
            btn.setWidth(320);
            btn.setHeight(40);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

请帮助解决同样的问题。但是添加单个按钮工作正常,但我需要在另一个下方添加许多按钮。

4

2 回答 2

3
public void AddAll() {
final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);

for(int i=0;i<4;i++)
{
    final Button btn = new Button(this);
    rl.addView(btn); 
    btn.setText("hello");

    btn.setWidth(320);
    btn.setHeight(40);
}
//////////////////////////////////////////////////////////
}

有关更多详细信息:-

如何以编程方式将按钮逐行添加到布局中?

或者

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView scrollView= new ScrollView(this);
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);                
    for (int i=0; i<10; i++){
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(i);                            
        TextView tv=new TextView(this);
        tv.setText("Row " + i);            
        ll.addView(tv);
        Button b = new Button(this);
        b.setTag(i);
        b.setText("Button " + i);            
        ll.addView(b);                    
        mainLayout.addView(ll);
    }
    scrollView.addView(mainLayout);
    setContentView(scrollView);
}
于 2013-03-12T10:42:55.403 回答
-1
public void AddAll() {
  LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
        layout.setOrientation(LinearLayout.HORIZONTAL); 

            for (int j = 0; j < 4; j++ ){
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                btnTag.setText("Button " + j);
                layout.addView(btnTag);
            }
        }
于 2013-03-12T10:48:33.053 回答