Two XML elements with same id

2020-07-07 11:14发布

I'm trying to modify two TextViews in exactly the same way. I thought I can give them same id and with findViewById() and setText() methods change those TextViews in two lines. But it seems only one TextView is changed.

Is there a way to do this? Or I have to make different ids for every element, get every element by findViewById() method and set it's text?

3条回答
冷血范
2楼-- · 2020-07-07 11:30

An id is unique for each View.So cannot be shared. What you can do is have both view ids fetched in the code and have conditons to modify the the text. Like if(id==id1 && id==id2) then edit the text.

查看更多
Animai°情兽
3楼-- · 2020-07-07 11:33

You have to define two different ids. There is no way to have a widget with the same id as another one as both are two different and independent widgets.

查看更多
一纸荒年 Trace。
4楼-- · 2020-07-07 11:46

View IDs are plain integers, so you can simply have an array of ids you want to change. For example:

int[] ids = { R.id.text1, R.id.text2, ... };
for (int id: ids) {
    TextView tv = (TextView) findViewById(id);
    tv.setText("Hello, World!");
}

Of course, it would be best to have ids as a static final class member. I.e.:

public class MyActivity extends Activity {
    private static final int[] textViewIDs = {
        R.id.text1,
        R.id.text2,
        ...
    }
    ...
}
查看更多
登录 后发表回答