2

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]);
2
  • No, findViewById() accepts int (View id) as parameter. Commented Mar 19, 2013 at 7:13
  • 2
    findViewById and R.drawable? seems legit.. Commented Mar 19, 2013 at 7:20

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I don't think your answer was wrong or irrelevant. So I'll neutralize the downvote.
0

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};

Comments

0

No this can't be done

You can do it other way like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.