[英]Change text in multiple TextViews with same Tag/ID
I have a problem with trying set multiple text views with the same text when it changes. 我在尝试使用相同的文本设置多个文本视图时遇到问题。 I have multiple
TextViews
that need to be set with the same values. 我有多个需要使用相同值设置的
TextViews
。 What I've been doing is just using each ID and setting the value of each independently but this doesn't seem very efficient. 我一直在做的只是使用每个ID并独立设置每个ID的值,但这似乎不是很有效。 Basically what I'm doing is:
基本上我正在做的是:
((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");
I'd prefer not to store each TextView as a global variable in my class because there are so many. 我不希望将每个TextView作为全局变量存储在我的类中,因为它有很多。 Is there a preferred approach to this or a simpler way to accomplish this?
是否有一种首选的方法来实现这一目标或更简单的方法?
You can group your Views using tags: Just use the same tag (for example group1 )for the textviews that are of the same group. 您可以使用标记对视图进行分组:只需对同一组的文本视图使用相同的标记(例如group1 )。 Then call
fix(yourRootView, "group1", "the_new_value");
然后调用
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.