将您在 xml 中的 EditText 布局设计为 my_item.xml 文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
在您的片段中添加一个LinearLayout 以在其中添加动态项目,并添加一个Button,如下所示:
<LinearLayout
android:id="@+id/ll_dynamicItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"></LinearLayout>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+" />
现在在 java 代码中,我们将 my_item 布局膨胀并将其添加到 ll_dynamicItems。我们还需要一个LinearLayout 的列表来存储膨胀的布局:
List<LinearLayout> myLayouts = new ArrayList<>();
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LinearLayout ll = (LinearLayout) getLayoutInflater().from(getApplicationContext()).inflate(R.layout.my_item, ll_dynamicItems, false);
myLayouts.add(ll);
ll_dynamicItems.addView(ll);
}
});
现在要获取第一个布局的第一个 EditText 值,您可以这样做:
((EditText) myLayouts.get(0).findViewById(R.id.et1)).getText()
获取第二个布局第三个EditText:
((EditText) myLayouts.get(1).findViewById(R.id.et3)).getText()
要读取所有 EditText 的值,您可以使用 for 跟踪列表;)