0

I have a question. I was searching how I can obtain a drawable object from a resource id. I have already found some ansers on stackoverflow, for example this one: How do you obtain a Drawable object from a resource id in android package?

However for some reason when I use this code I always get the same image, while I have three images in my res/drawable folder. I think I am overlooking a small thing but can't find the problem. Could somebody check my code for me?

So when I change R.drawable.img_1 to R.drawable.img_2 the image doesn't change.

Here is the code:

public class ShowPaintingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_painting);
        showImage();
    }
    public void showImage() {

        Drawable d = ContextCompat.getDrawable(this, R.drawable.img_1);
        ImageView image = (ImageView)findViewById(R.id.image);
        image.setImageDrawable(d);

    }
}
Community
  • 1
  • 1
L.B
  • 51
  • 1
  • 1
  • 10
  • I tried your code and everything is fine and worked for me. I copy/paste your same code so you have to check your resources name. – Robert Apr 22 '16 at 17:09
  • No, the resource names were fine, but i fixed the problem. Look at the update. Thanks for answering my question! – L.B Apr 22 '16 at 17:14
  • You should not update your question with the answer instead you have to post your solution as own answer. – Robert Apr 22 '16 at 17:32
  • Done! Thank for your advice Robert – L.B Apr 23 '16 at 07:27

1 Answers1

0

Fixed the problem. I had messed up my drawable folder. I think because renaming some files. Fixed the problem by doing the following.

1- go to android studio’s menu bar Build > Rebuild Project

2- go to android studio’s menu bar Build > Clean Project

3- got to android studio’s menu bar File > Invalidate Caches / Restart

L.B
  • 51
  • 1
  • 1
  • 10