[英]TextViews text change in a for loop
我想在Android Studio中的for循環中更改textViews的文本,如下所示:
對於i = 0 ------------> textView0設置文本“默認”
對於i = 1 ------------> textView1設置文本“默認”
對於i = 2 ------------> textView2設置文本“默認”
有可能這樣做嗎? 我不知道如何根據“ i”值更改循環內的textView id,有人可以幫助我嗎?
這是我的XML:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="--------------"
android:id="@+id/textView0"
android:layout_marginLeft="16dp"
android:layout_gravity="center_horizontal"
android:textSize="13dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="--------------"
android:id="@+id/textView1"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="16dp"
android:textSize="13dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="--------------"
android:id="@+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="16dp"
android:textSize="13dp" />
性能明智的好方法。
int[] textViews = {R.id.textView1, R.id.textView2, R.id.textView3};
String[] messages = {"one", "two", "three"};
for (int i = 0; i < 3; i++) {
TextView tv = (TextView) findViewById(textViews[i]);
tv.setText(messages[i]);
}
您也可以有一個標簽集合來獲取標簽表格。
List<String> labels = new ArrayList<>();
labels.add("Default 1");
labels.add("Default 2");
labels.add("Default 3");
int[] textViewIds = new int[3];
textViewIds[0] = R.id.text_view_a;
textViewIds[1] = R.id.text_view_b;
textViewIds[2] = R.id.text_view_c;
for (int i = 0; i < textViewIds.length; i++) {
TextView tv = (TextView) findViewById(textViewIds[i]);
tv.setText(labels.get(i));
}
好吧,如果您所有的文本視圖都與xml中當前處於相同的層次結構級別,則可以嘗試以下解決方案:
將整個內容包裝在一個父布局中,例如RelativeLayout。 然后,遍歷它:
int numberOfTextViews = layout.getChildCount();
for(int i = 0; i < numberOfTextViews; i++) {
((TextView)(afterSendingMail.getChildAt(i))).setText("Default");
}
還有另一種更好的方法來讀取android中的布局,drawable和id 資源ID
String[] messages = {"one", "two", "three"};
for (int i = 0; i < 3; i++) {
TextView tv = (TextView) findViewById(getResources().getIdentifier("textView" + i+1, "id", getPackageName()));
tv.setText(messages[i]);
}
在運行時它將讀取id
。 可能是您有100 ids
則無需將這些ID保存在數組中。
注意
並在Fragment 中將getActivity()與getResources()
和getPackageName()
。 有關詳細信息看看這個和這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.