Как динамически добавить несколько кнопок в строку в Android - PullRequest
0 голосов
/ 29 июля 2011

Кто-нибудь знает, как динамически добавить несколько строк в строку таблицы в Android?

Ответы [ 3 ]

3 голосов
/ 31 июля 2011

Вы можете попробовать это и посмотреть, если это то, что вы ищете.

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 голос
/ 29 июля 2011

Здесь макет является 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);

Если у вас уже есть строка в макете, просто выберите строку и добавьте кнопки в строку

0 голосов
/ 29 июля 2011

После 30 секунд поиска я нашел http://www.warriorpoint.com/blog/2009/07/01/android-creating-tablerow-rows-inside-a-tablelayout-programatically - это должно помочь вам, просто измените TextViews на кнопки.

...