Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two XML elements with same id

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?

like image 317
Seraphis Avatar asked Nov 10 '10 11:11

Seraphis


1 Answers

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,
        ...
    }
    ...
}
like image 120
Felix Avatar answered Sep 22 '22 04:09

Felix