如何在运行时添加具有动态ID的Android视图

3
我正在制作一个应用程序,在某个片段中,我需要一个可变数量的EditText。在布局下方有一个添加按钮,按下该按钮时应添加所需的具有ID的EditText,以便可以从中收集数据。
例如,如果布局开始为 Initial Layout 当我按下 + 按钮时,它应该像这样添加 Second Layout 因此,当我继续按下+按钮时,应自动获取一个带有所有编辑文本的布局。我需要一种方法来跟踪所有编辑文本的ID,以便稍后可以获取所有数据。
我该如何做?

你目前尝试了什么?给我们展示一些代码。 - Mehmet K
我还没有尝试过任何方法。虽然我想到了很多种方法,但是我无法找到实现它的方法 @Mehmet - Sriram R
为了动态添加元素,您可以从这里获取一些帮助。并且为了提供ID,您可以从这里获取一些有用的代码。 - UltimateDevil
考虑使用 ListViewRecyclerView - Mehmet K
2个回答

1

在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循环来遍历列表 ;)


0

实际上,您可以采用LinearLayout垂直方向,并在用户按下加号按钮时添加EditText,通过编程方式将其添加到布局中。您可以维护一些随机数字并将其相加。

       EditText ed = new EditText(this);

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

        ed.setInputType(2);

        ed.setLayoutParams(lparams);

        textFieldsLayout.addView(ed)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接