将小部件(EditText)添加到现有xml结构

时间:2014-02-01 10:40:20

标签: android android-widget

我为android活动设置了一个xml布局,它包含一个LinearLayout 一个ScrollView,一个带有两个按钮的TableLayout。

ScrollView本身包含另一个TableLayout,其默认数量为TableRows,比如说六个。 TableRows都是相同的类型 - 三个EditText小部件。

我想为用户提供添加或删除TableRows的选项,然后将其集成到TableLayout中。

我知道如何将Widgets添加到布局中,但不知道如何将它们集成到现有的xml结构中!

所以我的问题是如何为addView()方法指定布局父级,以便将TableRows和EditTexts添加/删除为最后一个ScrollView项。

我想使用“计数器”方法来监控TableRows的数量并为下一个项目提供ID。

实际的行应如下所示,每个新行应该是具有不同ID的副本

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

            <EditText
                android:id="@+id/MainExercise1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:hint="@string/MainExerciseHint" />

            <EditText
                android:id="@+id/MainReps1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:ems="10"
                android:hint="@string/MainRepsHint" />

            <EditText
                android:id="@+id/MainWeight1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:ems="10"
                android:hint="@string/MainWeightHint" />
        </TableRow>

1 个答案:

答案 0 :(得分:0)

// get the viewgroup I suppose it's tablelayout in your case    
TableLayout tl =(TableLayout) rootView.findViewById(R.id.your_table_layout);

//create a new tablerow with attributes you want
TableRow r = new TableRow(getActivity());

//create edittext as much as you want
EditText e1 = new EditText(getActivity());

//add edittext to tablerow
r.addView(e1);

//add tablerow to tablelayout
tl.addView(r);