Remove image resource of ImageButton [duplicate]

2019-06-18 00:12发布

问题:

This question already has an answer here:

  • Remove the image from a imageview Android [duplicate] 4 answers
  • How to clear an ImageView in Android? 16 answers

I have a transparent ImageButton. When clicked, the ImageResource of the button is set to a drawable in my drawable-hdpi folder (basically an image is shown on top of the transparent ImageButton). I'm using the ImageButton.setImageResource() method in order to do that. My question is, how can I remove the image resource so that there is only a transparent image button again. Of course, I need to be able to do this in java, not XML. I tried the following which failed to work: ImageButton.setImageResource(null); I also looked around a bit and couldn't find an answer... Thanks in advance for any help.

EDIT: Thank you all for your answers.. Péter Varga's answer did exactly what I needed so that's what i'm going with.

回答1:

Try setting imageButton.setImageResource(android.R.color.transparent).



回答2:

imageButton.setBackgroundResource(0);

Docs says:

The resource should refer to a Drawable object or 0 to remove the background



回答3:

Normally, people create null_image.xml resource file in drawable folder and use this resource whenever they need to clear background:

null_image.xml content:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="#0000" />
    <size
        android:width="1dp"
        android:height="1dp" />
</shape>

And when you need to clear background - just call:

ImageButton.setImageDrawable(R.drawable.null_image);

Don't know why CSimth did not post his comment as an answer... It was correct as for me



回答4:

I'm not sure if it works, but I think you could recycle the ImageButton's drawable.

Try something like:

ImageButton imbBtn = (ImageButton) findBiewById(R.id.imbBtn);

imgBtn.getDrawable().recycle();

I've never tried this before, let me know if it works to you.