0

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?

Nim
  • 25
  • 8

2 Answers2

0

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

gcorso
  • 154
  • 8
0

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.

Giovanni
  • 6,055
  • 2
  • 23
  • 44
  • Thank you for your answer. I tried imgchange.invalidate(); and then insert setBackgroundResource(R.drawable.pause), but no luck. I also tried the code ContextCompat but it is showing error – Nim Oct 22 '17 at 10:24
  • Wow, now it's working but image size is creating a problem. As it is now exceeding and overlapping with TextView – Nim Oct 22 '17 at 10:43
  • You can give your ImageView a predefined height and width, you can also specify the scaletype. – Giovanni Oct 22 '17 at 10:44
  • Yup, u r right. Thanks a lot. Can I also add animation to this ? like when music play animation start, instead of just changing one image. Is that i can do in same way? As for this I create one anim.xml file in drawable – Nim Oct 22 '17 at 10:53
  • Yes, but we cannot discuss that here. Please mark this as an answer if it helped you. – Giovanni Oct 22 '17 at 10:59