0

Here's the code:

String id = "R.drwable.br" + mQuestionNumber;
mSlikaNastavi.setImageDrawable(getDrawable(id));

error found on getDrawable(id): getDrawable (int) in Context cannot be applied to (java.lang.String)

mSlikaNstavi is ImageView, and I would like to change image from java. I cant write in R.drawable.br2 in getDrwable() because every time mQuestionNumber is different.

Anatolii
  • 14,139
  • 4
  • 35
  • 65

3 Answers3

1

A drawable Id needs to be int rather than String. You can get the relative int Id using getIdentifier()

Instead of

mSlikaNastavi.setImageDrawable(getDrawable(id))

Use

String id = "br" + mQuestionNumber;
mSlikaNastavi.setImageDrawable(getDrawable(getResources().getIdentifier(id, "drawable", getPackageName())));`
Sagar
  • 23,903
  • 4
  • 62
  • 62
1

I guess you have drawables like br1, br2, br3,... and you think that by concatenating R.drawable.br and mQuestionNumber you get the id of the drawable but this is not the case.

do this:

int id = getResources().getIdentifier("br" + mQuestionNumber, "drawable", getPackageName());
mSlikaNastavi.setImageDrawable(getDrawable(id));
0

Here you need to extract the Drawable Id by passing your own id value, instead of the ids which are present in R.java

So for that getIdentifier method is used where you need to provide the drawable name, type of the resource which is "drawable" in your case, and the packageName where Android will search the drawable from.

    int drawableId = getResources().getIdentifier("br" + mQuestionNumber,"drawable",getPackageName());

After the id is found, use it to show it in imageView using setImageDrawable() and as it required Drawable get the Drawabel from its iD using getDrawable() passing in the ID.

    mSlikaNastavi.setImageDrawable(getResources().getDrawable(drawableId));

So the code is:

    int drawableId = getResources().getIdentifier("br" + mQuestionNumber,"drawable",getPackageName());
    mSlikaNastavi.setImageDrawable(getResources().getDrawable(drawableId));
Anmol
  • 448
  • 2
  • 6