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.

4 Answers 4

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

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)));
      ...
     }

Comments

1

Have a look at this question:

1 Comment

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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.