0

I'm very new to Java. So pardon me for asking such simple question.


To set the background-image of a view, I can do that by

int TheButton = R.drawable.button1;   
button.setBackgroundResource(TheButton);

But how can this be done if I want to use a variable to specify the R object?

int a = 1;
int TheButton = R.drawable["button"+a]; //this is what I'll do in javascript...  
button.setBackgroundResource(TheButton);

4 Answers 4

1

Try this :

         String variable="button" + a;
         int Button = getResources().getIdentifier(variable, "drawable",  getPackageName()); 
         //Whatever you want to do..
Sign up to request clarification or add additional context in comments.

Comments

1

When we use R.drawable.button1 it refers to a int element in drawable class which is in R class. R.java is a self generated class in gen folder.

So int TheButton = R.drawable["button"+a]; will not work.

if you want to assign a particular id from js then you can directly use the code copied from R.java like int TheButton =0x7f080002; copied from R.java

OR

int TheButton = getResources().getDrawable(R.drawable.button1);

Comments

1

In Android you can't access resources that way, because when android compiles your application it translates all these fields to Constant Value (int).

So you need to write your own mapper to get the results you're expecting, for example you can put all of the related resources in an array:

int[] myResourceArray = new int[]{R.drawable.first, R.drawable.second ...};
button.setBackgroundResource(myResourceArray[0]);
...
button.setBackgroundResource(myResourceArray[1]);

Or you can use the way @Sercan Suggested, but according to android's documentations they discourage using it for performance reasons. take a look here : getIdentifier()

Comments

0

Ok first of all, since in java variables are typed, you can't add an int to a character sequence.

Secondly you can't use a string to call a public variable from a class (in this case the auto generated R class).

Third point, if tou want to use many drawable on a Button and switch between them i suggest you to use the level-list drawable or the state-liste drawable.

have a look at: http://developer.android.com/guide/topics/resources/drawable-resource.html

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.