How to change the image in ImageView

Asked 2 years ago, Updated 2 years ago, 100 views

<ImageView 
      android:id="@+id/articleImg"
      style="@style/articleImgSmall_2"
      android:src="@drawable/default_m" />

I set the image of the image view in xml. What I need is to change the image from the code. I want to erase the old image and change it to a new one

myImgView.setBackgroundResource(R.drawable.monkey); I tried it and it worked, but it felt like I was building a new image on top of my old image. What I want is to completely replace old images with new ones.

What should I do?

android imageview android-imageview

2022-09-21 17:17

1 Answers

setBackgroundResource() is a method that puts Monkey as the background.

Use setImageResource(). myImgView.setImageResource(R.drawable.monkey); This is how you do it. Or myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey)); Write setImageDrawable() in this way. For reference, getResources().getDrawable() has been deprecated from API22, so

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()); You can write it like this.


2022-09-21 17:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.