【问题标题】:How do I add android views in run time with dynamic ID's如何在运行时使用动态 ID 添加 android 视图
【发布时间】:2017-09-18 12:08:04
【问题描述】:

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

例如,如果布局以

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

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

我该怎么做呢???

【问题讨论】:

  • 到目前为止您尝试过什么?给我们看一些代码
  • 我还没有尝试过任何东西。我想了很多方法,但我想不出办法@Mehmet
  • 对于动态添加元素,您可以从here 获得一些帮助。要提供 ID,您可以从 here 获取一些有用的代码
  • 研究使用ListViewRecyclerView

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


【解决方案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 跟踪列表;)

【讨论】:

    【解决方案2】:

    实际上,您可以在用户按下加号按钮时采用线性布局垂直方向并添加编辑文本,您可以通过编程方式添加到布局中。 你维护一些你添加的随机数

           EditText ed = new EditText(this);
    
            ed.setId(1);
            ed.setText("" + i);
    
            ed.setInputType(2);
    
            ed.setLayoutParams(lparams);
    
            textFieldsLayout.addView(ed)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 2011-12-22
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多