[英]Android - Different Ids for the same include Layout
我有一個布局,我必須多次包含。 它由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,因為我多次包含相同的Layout。 有沒有辦法以編程方式包含布局並始終更改每個包含的布局的ID?
我要做的是,當您需要訪問包含布局的特定實例的視圖時:
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);
您可以動態創建TextView,然后使用TextView.setId(int id)
設置該View的id,以便稍后可以使用新id調用它。
對於每個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
您可以使用它來更改TextView ID
TextView textview = new TextView(this); textview.setId(int id);
據我所知,沒有辦法做到這一點。 如果希望XML布局中的ID是唯一的,則必須使用<include>
創建布局。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.