如何将多个按钮,动态添加到行中的Android
问题描述:
是否有人知道如何将多个按钮添加到表行动态Android中?
Does anybody know how to 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中:
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>
您Activity类:
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 );
}
}
}
希望它帮助。