繁体   English   中英

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

[英]Change text in multiple TextViews with same Tag/ID

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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