In the Java code of an Android project if you want the reference for a view resource you can do something like:
View addButton = findViewById(R.id.button_0);
In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0
"?
I'd like to refer to a button by "R.id.button_%i
" where %i
is replaced by some valid index.
The Android SDK provided a method: findViewById() . Functionality-wise, this method performs a singular task — it will give you the reference to the view in XML layouts by searching its ID. And if nothing is found, it will give you the good old NULL , which is said to be the 1-billion dollar mistake by its creator.
FindViewById(Int32) Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .
int resID = getResources().getIdentifier("button_%i", "id", getPackageName()); View addButton = findViewById(resID);
where %i
is replaced by some valid index.
The getResources()
method belongs to the Context
class, so you can use that directly from an Activity
. If you are not inside an activity, then use a context to access: (myCtxt.getResources()
).
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