tags:

views:

60

answers:

2

I have an xml layout that will display a grid made up of textviews within tablerows. The textview names are cell00, cell01, etc. At runtime, my program will determine which cell needs to be changed.

Is there a way get format a name so that it can be passed to the findViewById method at runtime? For example, if cell00 is needed, how can I generate the parm in this code?

TextView currcell = (TextView) findViewById(R.id.cell00) 

Something like “cell”+00 doesn’t compile because the findViewById method doesn’t accept a String type. I don’t want have every textview name in the grid hardcoded in the program – there must be a better way.

Thank you for any help you can provide.

A: 

You could use reflection to find the integer value of a named variable in R.id.

Class clazz = R.id.class;
Field f = clazz.getField("cell" + "00");
int id = f.getInt(null);  // pass in null, since field is a static field.
TextView currcell = (TextView) findViewById(id); 

Keep in mind that reflection can be slow. If you do it a lot, you might want to cache values or come up with a different way.

Mayra
Very helpfull. I really appreciate your time. I have entered the code and got a clean compile. I should have come to this site weeks ago.
greenset
A: 
int id = getResources().getIdentifier("cell00", "id", getPackageName());
TextView currcell = (TextView) findViewById(id); 

Like Mayra's way the code also uses reflection, so be careful.

Konstantin Burov
Ty for the suggestion. I'm trying both ways to see which works best for my needs.
greenset