1

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

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

3 回答 3

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

就是这样,你完成了。

于 2013-11-05T10:24:15.267 回答
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]);
}
于 2013-11-05T10:37:53.373 回答
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);
于 2013-11-05T10:18:38.610 回答