Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android and getting a view with id cast as a string

Tags:

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.

like image 465
SK9 Avatar asked Jan 18 '11 23:01

SK9


People also ask

How do I find view by ID?

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.

Which method is get view ID in Android Studio?

FindViewById(Int32) Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .


1 Answers

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()).

like image 177
Cristian Avatar answered Sep 27 '22 23:09

Cristian