1

Using java for Android, I have come across a problem:

for(int a = 0; a < 26; a++){
    textViewArray[a] = (TextView) findViewById(R.id.(alphabet[a]));
}

I have 26 TextViews in an xml file with the ids A, B, C, D, ...Z I need the above to become R.id.A, R.id.B, R.id.C, ...R.id.Z when it is run. The above is one of my attempts which for obvious reasons doesn't work. I have thought of using

int[26] = new int[]{R.id.A, R.id.B, R.id.C .... R.id.Z};

then using those array entries in the above for loop but is there a neater way to do it? Possibly converting a string ( "R.id." + (alphabet[a]) ) to code and letting it run as usual to find the id?

P.S. alphabet is a String array containing A, B, C ... Z in the above example

2
  • 26 TextViews? That sounds a bit silly. Are you sure you shouldn't be using an AdapterView; i.e. a ListView? Commented Nov 23, 2013 at 3:54
  • To be honest I didn't know about these classes when I asked the question. Gallery seems to fit my needs the best out of the adapter views I looked at, but it doesn't fit them well so I think I'll stick to the text views. Commented Nov 23, 2013 at 6:31

1 Answer 1

5

Resources.getIdentifier(). Keep in mind that this function is quite slow, so don't use it unless you have to.

In your case, I'd stick with the array you proposed, that's the better approach.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, more generally, is there a way to convert string to code?
You mean convert source code to bytecode? Not possible without a compiler.
Ah of course. I was thinking that it might be possible more generally because it is sort of possible in this specific example

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.