<?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 ");
}
我想更改每个填充的textview的文本,但上面的代码只更改第一个textview的文本。
答案 0 :(得分:0)
上面的代码错误,您应该先设置文本并将其添加到下一个父视图中。
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);
}
此代码可以正常工作..
答案 1 :(得分:0)
正如Bonatti所指出的,findViewById()
三次定位同一资源。因此,我没有直接访问template_title_TV
,而是通过container_template
视图访问它:
TextView title_tv_template = (TextView)container_template.findViewById(R.id.template_title_TV);