Joseph Genio
Joseph Genio

Reputation: 23

findViewById function using string variables

i am currently facing a problem, is it possible to use the function "findViewById()" like this?

String[] names{ "a", "b"};
findViewById(R.drawable.names[0]);

Upvotes: 2

Views: 1458

Answers (4)

Tushar
Tushar

Reputation: 8049

EDIT: Just so you know, you can only call findViewById on R.id types. Thus, your code is bound to fail since you're calling it on R.drawable types.

Try getIdentifier(). Documentation

int resourceId = getResources().getIdentifier(names[0], "drawable", getPackageName());
findViewById(resourceId);

Note: The Android Documentation says:

use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

In this case, it'll probably be better if you defined an array of int, and those contained the ids of the drawable resources.

Upvotes: 3

Rohit
Rohit

Reputation: 1001

No this can't be done

You can do it other way like

int[] ids={R.drawable.a,R.drawable.b};
findViewById(ids[0]);

Upvotes: 0

Hardik Joshi
Hardik Joshi

Reputation: 9507

findViewById() accept int not string. So you can use like..

int[] txtViewIdsform1;
txtViewIdsform1 = new int[] { R.drawable.txt_phone1, R.drawable.txt_phone2,
                R.drawable.txt_fax, R.drawable.txt_contact_name, R.drawable.txt_contact_ph};

Upvotes: 0

Rahul
Rahul

Reputation: 45060

No you cannot do that, but instead there is a work around for that. Try something like this:-

String[] names{ "a", "b"};
int drawableId = this.getResources().getIdentifier(names[0], "drawable", this.getPackageName());
findViewById(drawableId);

Where this is an Activity, written just to clarify.

In case you want a String in strings.xml or an identifier of a UI element, substitute the "drawable"

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

I must warn you, this way of obtaining identifiers is really slow, use only where needed.

Upvotes: 1

Related Questions