Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create findViewById parm dynamically or programmatically at runtime

Tags:

android

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.

like image 254
greenset Avatar asked Sep 27 '10 18:09

greenset


1 Answers

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.

like image 60
Cheryl Simon Avatar answered Dec 16 '22 23:12

Cheryl Simon