如何在动态ID的运行时添加android视图

时间:2017-09-18 12:08:05

标签: android android-layout android-fragments android-edittext

我正在创建一个应用程序,在某个片段中,我需要片段中可变数量的EditTexts。我在布局下面有一个添加按钮,按下时应该添加所需的编辑文本ID,以便我可以从中收集数据。

例如,如果布局开始于 Initial Layout

当我按下+按钮时,它应该添加 Second Layout

因此,当我一直按下+按钮时,我应该自动获得一个包含所有编辑文本的布局。 我需要一种方法来跟踪所有编辑文本的ID,以便我以后可以获取所有数据。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

实际上,只要用户按下加号按钮,您就可以采用linearlayout垂直方向并添加edittexts,以编程方式添加到布局。 你保留一些你添加它的随机数

       EditText ed = new EditText(this);

        ed.setId(1);
        ed.setText("" + i);

        ed.setInputType(2);

        ed.setLayoutParams(lparams);

        textFieldsLayout.addView(ed)

答案 1 :(得分:0)

将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;)

跟踪列表
相关问题