0

我在尝试使用相同文本更改时尝试设置多个文本视图时遇到问题。我有多个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 作为全局变量存储在我的班级中,因为有很多。是否有首选方法或更简单的方法来完成此操作?

4

1 回答 1

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);
            }
        }
    }
于 2013-10-01T15:38:44.510 回答