kalpitha
kalpitha

Reputation: 23

Accessing id names in android using loops

Lets say I have different paragraphs in html with id's like para1, para2 and so on. I can access the elements through the id names in a loop using javascript by enclosing the suffixed numbers in quotes. Can the same be done in android using either java or xml?

For ex. If I had three TextViews in my application with id's text1, text2, text3, In the regular way, I'd have to do this (in Java):

TextView t1 = (TextView) findViewById(R.id.text1);
TextView t2 = (TextView) findViewById(R.id.text2);
TextView t3 = (TextView) findViewById(R.id.text3);

So is there any way I can access the id name in a loop using arrays like

TextView b[i] = (TextView) findViewById(R.id.text[i]);

or

TextView b[i] = (TextView) findViewById(R.id.text\"i\"); (like in javascript)

Upvotes: 1

Views: 74

Answers (1)

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

No, to achieve this you'll have to create an array of ids:

@IdRes int[] ids = new int[] { R.id.button1, R.id.button2, R.id.button3 };

TextView textViews[] = new TextView[3];

for (int i = 0; i < textViews.length; i++) {
    textViews[i] = (TextView) findViewById(ids[i]);
}

Upvotes: 2

Related Questions