我在尝试使用相同文本更改时设置多个 TextView 时遇到问题。我有多个需要设置相同值的 TextView
。我一直在做的只是使用每个 ID 并独立设置每个 ID 的值,但这似乎不是很有效。基本上我正在做的是:
((TextView)findViewById(R.id.text_1_1)).setText("text 1");
((TextView)findViewById(R.id.text_1_2)).setText("text 1");
((TextView)findViewById(R.id.text_2_1)).setText("text 2");
((TextView)findViewById(R.id.text_2_2)).setText("text 2");
.....
((TextView)findViewById(R.id.text_5_1)).setText("text 5");
((TextView)findViewById(R.id.text_5_2)).setText("text 5");
我不想将每个 TextView 存储为类中的全局变量,因为数量太多了。是否有首选方法或更简单的方法来实现此目的?
最佳答案
您可以使用标签对 View 进行分组:只需对同一组的 TextView 使用相同的标签(例如 group1)。然后调用 fix(yourRootView, "group1", "the_new_value");
protected void fix(View child, String thetag, String value) {
if (child == null)
return;
if (child instanceof ViewGroup) {
fix((ViewGroup) child, thetag, value);
}
else if (child instanceof TextView) {
doFix((TextView) child, thetag, value);
}
}
private void fix(ViewGroup parent, String thetag, String value) {
for (int i = 0; i < parent.getChildCount(); i++) {
fix(parent.getChildAt(i), thetag, value);
}
}
private void doFix(TextView child, String thetag, String value) {
if(child.getTag()!=null && child.getTag().getClass() == String.class) {
String tag= (String) child.getTag();
if(tag.equals(thetag)) {
child.setText(value);
}
}
}
关于java - 更改具有相同标签/ID 的多个 TextView 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119893/