Home » Android » Change image in ImageView

Change image in ImageView

Posted by: admin November 1, 2017 Leave a comment

Questions:

In list_item.xml file I have a ImageView and one TextView. The code of ImageView is given as

 <ImageView
    android:id="@+id/play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/play"/>

In main activity (main_activity.java is connected with activity_main.xml, which have one ListView), the music is playing well when user click on music (onItemClick) from list set with setAdapter. Now I want to change the image of this ImageView, when music start to play, when . So I inserted the code as given below:

View inflatedView = getLayoutInflater().inflate(R.layout.list_item, null);
ImageView imgchange = (ImageView)inflatedView.findViewById(R.id.play);
imgchange.setImageResource(R.drawable.pause);

But it is not working. I also tried

android:src="@drawable/imagename"

I also tried

imgchange.setBackgroundResource(R.drawable.pause);

Looking for valuable advise as how can I do it or where is the mistake?

Answers:

I would use the new ContextCompat instead of setBackgroundResource(), like this:

imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.pause));

You can pass your Activity as the Context. If that does not work, you can also try to invalidate your view, which will force a redraw.

Questions:
Answers:

I had a similar problem in the past and it was caused by the fact that the layout didn’t updated itself. Try to refresh the layout of the view after you changed the image as described here android redraw layout programmatically