【问题标题】:add row in TableLayout on onClick event [duplicate]onClick事件在TableLayout中添加行[重复]
【发布时间】:2013-10-16 17:05:44
【问题描述】:

我有一个TableLayout

<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*" >

<TableRow
android:id="@+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <TextView
         android:id="@+id/textView2"
        android:text="Day High"
        android:textStyle="bold" >
     </TextView>

    <TextView
        android:id="@+id/textView3"
         android:gravity="center_horizontal"
        android:text="28°F" >
     </TextView>

     <TextView
        android:id="@+id/textView4"
         android:gravity="center_horizontal"
        android:text="26°F" >
     </TextView>    

</TableRow>
</TableLayout>

还有一个Button

<Button
android:id="@+id/addItemTableRow"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="31dp"
android:textColor="@android:color/white"
android:text="Add row" />

我无法通过单击button 在表格中添加新行。

有什么想法我该如何实现这个任务?

【问题讨论】:

  • 您是否尝试过以编程方式创建新的 TableRow 和 TextView?
  • 是的,我正在尝试以编程方式创建它们
  • 所以请展示您的代码并解释为什么它没有按预期工作。
  • 对不起,我没有得到代码(代码在另一台电脑上)。你能给我一段能完全正常工作的代码吗?

标签: android android-button android-tablelayout


【解决方案1】:

在 Activity 类的 onCreate 方法上试试这个:

  //define a onClickListener for your button
    Button btnAddItem = (Button) findViewById(R.id.addItemTableRow);
    btnAddItem.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                            //create a new row to add
            TableRow row = new TableRow(YourActivity.this);
                            //add Layouts to your new row
            TextView txt = new TextView(YourActivity.this);
            txt.setText("New Row"); 
            row.addView(txt);
            //add your new row to the TableLayout:
            TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
            table.addView(row);

        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多