簡體   English   中英

使用 onClickListener 動態地將多個表格行添加到表格布局中

[英]Adding multiple table rows into table layout using onClickListener dynamically

我正在使用onClickListener在我的表格布局中創建一個新的表格行。 我已經為我的表格行定義了所有值,盡管我想添加多行,但它工作正常。

    final TableLayout tl=(TableLayout)findViewById(R.id.tbl);
    final TableRow tr1 = new TableRow(this);
    final TextView textview1 = new TextView(this);
    final TextView textview2 = new TextView(this);
    final Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textview1.setText("B");
            textview1.setBackgroundResource(R.color.darkgrey);
            textview1.setGravity(Gravity.CENTER);
            textview1.setPadding(50, 50, 50, 50);
            textview2.setText("A");
            textview2.setBackgroundResource(R.color.darkgrey);
            textview2.setGravity(Gravity.CENTER);
            textview2.setPadding(50, 50, 50, 50);
            tr1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
            tr1.addView(textview1);
            tr1.addView(textview2);
            tl.addView(tr1);
        }
    });

XML

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="*"
    android:id="@+id/tbl"
    android:layout_below="@+id/btn">

    <View
        android:layout_height="2dip"
        android:background="#FFFFFF" />
</TableLayout>

所以我點擊了一次按鈕,新的表格行出現,再次點擊后應用程序崩潰。

如何動態地將多個表格行添加到我的表格布局中? 我想過使用 for 循環,但我不確定應用它的正確方法。

編輯:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.none.myapplication, PID: 9775
                  java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

如果沒有確切的錯誤消息,很難判斷,但我覺得這是因為您創建了最終變量,然后嘗試再次添加它們。 您是否嘗試過在 OnClickListener 中創建新的表格行和文本視圖?

使用 for 循環在您的情況下沒有用,因為您確實希望在單擊時創建該行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM