将小部件(Edittext)添加到现有的XML结构中



我已经为Android活动设置了一个XML布局,其由固定的线层组成滚动浏览,一个带有两个按钮的tablayout。

scrollview本身包含了其他带有默认数量的tablerows的tableLayout,可以说六个。tablerows都是相同类型的 - 三个Edittext小部件。

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

我知道如何将小部件添加到布局中,但并不是如何将它们集成到现有的XML结构中!

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

我想使用一种"计数器"方法来监视表格的数量并为下一个项目提供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>
// 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);

最新更新