使用相同的标记/ ID更改多个TextView中的文本

时间:2013-10-01 15:14:32

标签: java android

我在尝试使用相同的文本设置多个文本视图时遇到问题。我有多个TextViews需要使用相同的值进行设置。我一直在做的只是使用每个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存储为我的类中的全局变量,因为它有很多。是否有一种首选方法可以实现这一目标或更简单的方法?

1 个答案:

答案 0 :(得分:2)

您可以使用标记对视图进行分组:只需对同一组的文本视图使用相同的标记(例如 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);
            }
        }
    }