[英]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.