如何在Android中动态添加多个按钮

时间:2011-07-29 05:21:04

标签: android android-layout dynamic row

有人知道如何在Android中动态地向表格行添加多个按钮吗?

3 个答案:

答案 0 :(得分:3)

你可以尝试一下,看看它是不是你想要的。

main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
    <Button android:text="Button" android:id="@+id/button1"
    android:layout_height="wrap_content"       
    android:layout_width="wrap_content"/>
    <TableLayout android:id="@+id/tableLayout1"
    android:layout_height="wrap_content" android:layout_width="fill_parent" />
</LinearLayout>

您的活动课程:

public class mainActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.main );
        Button b = (Button) findViewById( R.id.button1 );
        b.setOnClickListener( this );
    }

    @Override
    public void onClick(View v) {   
        TableLayout table = (TableLayout) findViewById( R.id.tableLayout1 );

        int buttonsInRow = 0;
        int numRows = table.getChildCount();
        TableRow row = null;
        if( numRows > 0 ){
            row = (TableRow) table.getChildAt( numRows - 1 );
            buttonsInRow = row.getChildCount();         
        }

        if( numRows == 0 || buttonsInRow == 3 ){
            row = new TableRow( this );
            table.addView( row );
            buttonsInRow = 0;
        }
        if( buttonsInRow < 3 ){
            Button b = new Button( this );
            row.addView( b, 100, 50 );
        }
    }
}

希望它有所帮助。

答案 1 :(得分:1)

这里布局是一个TableLayout。如果你想动态添加一行,那行中的按钮可以使用下面的代码

TableRow tr1=new TableRow(this);
                    Button tv=new Button(this);
                tv.setText("");
                tr1.addView(tv,250,30);
                Button tv1=new Button(this);
                tv1.setText("");
                tr1.addView(tv1,100,30);
                layout.addView(tr1);

如果布局中已有行,则只需获取行并向行添加按钮

答案 2 :(得分:0)

搜索30秒后,我发现http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically - 这应该可以帮助您,只需将TextViews更改为按钮。