开发者

How to add multiple buttons to a row dynamically in Android

Does anybody know how to开发者_如何学Python add multiple buttons to a table row dynamically in Android?


You can try this and see if it's what your are looking for.

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>

Your Activity class:

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

Hope it helps.


Here layout is a TableLayout.If you want to add a row dynamically and buttons in that row can use the follwoing code

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

If you already have row in the layout then just fetch the row and add buttons to the row


After searching for 30 sec I found http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically - this should help you, just change TextViews to Buttons.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜