在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
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="+" />
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) myLayouts.get(0).findViewById(R.id.et1)).getText()
((EditText) myLayouts.get(1).findViewById(R.id.et3)).getText()
为了读取所有EditText的值,你可以使用for循环来遍历列表 ;)
实际上,您可以采用LinearLayout垂直方向,并在用户按下加号按钮时添加EditText,通过编程方式将其添加到布局中。您可以维护一些随机数字并将其相加。
EditText ed = new EditText(this);
ed.setId(1);
ed.setText("" + i);
ed.setInputType(2);
ed.setLayoutParams(lparams);
textFieldsLayout.addView(ed)