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

时间:2013-11-05 10:16:24

标签: android button dynamically-loaded-xap

我想创建一个动态添加按钮的布局。在这里,要添加的按钮数量取决于运行时间,即根据服务器返回的按钮数量,我想添加按钮。

 for (int k = 1; k < 100; k++) {
            TableRow row = new TableRow(this);

            innerloop:
           for (int  l = 1; l <4; l++) {
                  btn = new Button(this);
                  TableRow.LayoutParams tr= new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                  layout.setWeightSum(12.0f);
                  tr.weight=0;
                    btn.setLayoutParams(tr); 
                  btn.setTextColor(a);
//                      btn.setLayoutParams(params);
                  btn.setHeight(150);
//                      Log.v("y", "how much"+size.x+"  "+size.y);
                  btn.setWidth(150);
                  btn.setId(idb);
                  btn.setOnClickListener(this);
                  btn.setText("Button " + idb);
//                      Log.v("idb", "created"+" "+btn.getId());
                  row.addView(btn);
                  }
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我希望你要在容器布局中添加按钮。

  LinearLayout containerLayout = (LinearLayout) findViewById(R.id.parentLayout);
        Button btnDynamic = new Button(YourActivity.this);
        btnDynamic.setText("Click to get values");
        LinearLayout.LayoutParams layoutParams = new  LinearLayout.LayoutParams(
                height,width);
        layoutParams.setMargins(5, 5, 5, 5); // left, top, right, bottom
        btnDynamic.setLayoutParams(layoutParams);
        containerLayout.addView(btnDynamic);

就是这样,你已经完成了。

答案 2 :(得分:0)

int flag=4;//some value returened by server.
TableLayout tl = (TableLayout)findViewById(R.Id.tl);
Button btn[] = new Button[flag];
TableRow row[] = new TableRow[flag];
TableRow.LayoutParams tr= new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

for(int i = 0; i<flag;i++)
{
                  btn[i]= new Button(this);    
                  row[i]= new TableRow(this);   

                  row[i].setLayoutParams(tr); 
                  btn[i].setTextColor(Color.RED);
                  btn[i].setHeight(150);
                  btn[i].setWidth(250);
                  btn[i].setOnClickListener(new OnClickListener() 
                  {
                    @Override
                    public void onClick(View v) 
                    {
                      //do something here.
                    }
                  });
                  btn[i].setText("this is Button " + flag);
                  row[i].addView(btn[i]);
                  tl.addView(row[i]);
}