【问题标题】:How to set different texts in the TextViews populated with inflater?如何在填充有充气机的 TextView 中设置不同的文本?
【发布时间】:2017-09-17 07:48:37
【问题描述】:

模板.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_below="@+id/header"
    android:orientation="horizontal"
    android:id="@+id/template_linear_layout_container"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:id="@+id/template_linear_layout">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/template_title_TV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="ALL"
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

我在 template.xml 中创建了一个 TextView,并使用 inflater 在 parent_view 中填充了 template.xml 的线性布局。

for(int i=0;i<3;i++){
    View container_template = getLayoutInflater().inflate(R.layout.templates, parent_layout, false);
    parent_layout.addView(container_template);
    TextView title_tv_template = (TextView) findViewById(R.id.template_title_TV);
    title_tv_template.setText(1+i+"text changed ");
}

我想更改每个填充文本视图的文本,但上面的代码仅更改第一个文本视图的文本。

【问题讨论】:

  • ID 是一个数字,因为它们始终指向相同的 id,因此它始终指向相同的资源(TextView)。您需要为每个不同的View 提供一个 ID,或者让它们在另一个唯一的 View.. 中有一个单独的实例。所以一个“mainLayout”,带有 3 个“LinearLayout”(a,b,c),然后使用 mainLayout.a.title , mainLayout.b.title, mainLayout.c.title

标签: android android-layout textview layout-inflater


【解决方案1】:

上面的代码是错误的,你应该先设置文本,然后添加到父视图..

for(int i=0;i<3;i++){
    View container_template = getLayoutInflater().inflate(R.layout.templates, parent_layout, false);
    TextView title_tv_template = (TextView) container_template. findViewById(R.id.template_title_TV);
    title_tv_template.setText(1+i+"text changed ");
    parent_layout.addView(container_template);
}

此代码将起作用..

【讨论】:

    【解决方案2】:

    正如Bonatti 指出的那样,findViewById() 三次针对同一资源。所以,我没有直接访问template_title_TV,而是通过container_template视图访问:

    TextView title_tv_template = (TextView)container_template.findViewById(R.id.template_title_TV);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多