简体   繁体   中英

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. What I've been doing is just using each ID and setting the value of each independently but this doesn't seem very efficient. 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. 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. Then call 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);
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM