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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With