我有一个布局,我必须多次包含。它由TextView
和ImageView
:
<ImageView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:background="@drawable/back2"
android:id="@+id/id_1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/id_2"
android:textSize="15dp"
android:typeface="sans"
android:textColor="#ffffff" />
现在我想以编程方式设置文本,但我面临的问题是,TextView
现在总是具有相同的ID,因为我多次包含相同的布局。有没有办法以编程方式包含布局并始终更改每个包含的布局的ID?
答案 0 :(得分:5)
当您需要访问所包含布局的特定实例的视图时,我要做的是:
ViewGroup instance = (ViewGroup) findViewById(R.id.included1); // Replace ViewGroup with whatever your particlar type is
ImageView iView = (ImageView) instance.findViewById(R.id.id_1);
TextView tView = (TextView) instance.findViewById(R.id.id_2);
答案 1 :(得分:2)
您可以动态创建TextView,然后使用TextView.setId(int id)
设置该视图的ID,以便稍后可以使用新ID调用它。
答案 2 :(得分:1)
对于每个textview
将行android:id="@+id/id_2"
中的ID更改为其他ID。
例如:
android:id="@+id/id_4"
要以编程方式添加它们,您可以执行以下操作:
TextView Label3 = new TextView(this);
Label3.setId(300);
Label3.setTextAppearance(this, android.R.attr.textAppearanceMedium);
Label3.setLayoutParams(labelParams);
Label3.setText("My textViewCaption:");
ll3.addView(Label3);
如果您将Label3设置为全局变量,则可以通过setText
以编程方式,您可以循环浏览并在循环时设置ID
答案 3 :(得分:1)
您可以使用它来更改TextView ID
TextView textview = new TextView(this);
textview.setId(int id);
答案 4 :(得分:0)
据我所知,没有办法做到这一点。如果您希望XML布局中的ID是唯一的,则必须使用<include>
创建无布局。