簡體   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