4

Typical way to reference android control is something like this:

TextView tv = (TextView)findViewById(R.id.tv);

Where R.id.tv is integer referencing my xml control.

The thing is I would like to make reference using string "R.id.tv". Is that possible?

Let's say I have multiple controls:

tv1,
tv2,
tv3,
tv4,
tv5,

How would I put this into some sort of loop and interate through controls. I am thinking I would use loop counter to reference different controls. How's that to be done? Thanks.

Nikhil
  • 16,194
  • 20
  • 64
  • 81
bobetko
  • 5,019
  • 14
  • 58
  • 85

4 Answers4

3

One approach is to put the ids into an array and reference by subscript.

int[] ids = { R.id.tv1, R.id.tv2 /* etc. */ };
for (int i = 0; i < ids.length; ++i) {
    TextView tv = (TextView)findViewById(ids[i]);
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
2

Try next

private int getIdResourceByName(String aString)
{
  String packageName = "com.myProject.myPackage"; // set your package name here
  int resId = getResources().getIdentifier(aString, "id", packageName);
  return resId;
}

...

  for (int i = 1; i<=5; i++) {
      TextView tv = (TextView) findViewById(getIdResourceByName("tv" + Integer.toString(i)));
      ...
     }
Michael Sh
  • 21
  • 1
1

Have a look at this question:

Community
  • 1
  • 1
dave.c
  • 10,910
  • 5
  • 39
  • 62
  • thank you. I was looking at getIdentifier but I wasn't quite sure how to use it properly. Example you linked illustrates exactly what I wanted to achieve. – bobetko Feb 09 '11 at 20:07
1

I don't understand why you'd want to do this, it's pretty ugly, inefficient, and likely to cause maintenance issues and bugs.

Why not use a collection (e.g. ArrayList) to store references to all the controls?

Ollie C
  • 28,313
  • 34
  • 134
  • 217