Remove background drawable programmatically in Android
I want to remove the background drawable @drawable/bg
pro开发者_如何转开发grammatically.
Is there a way to do that?
Currently, I have the following XML in my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget29"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/bg">
</RelativeLayout>
Try this
RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29);
relative.setBackgroundResource(0);
Check the setBackground functions in the RelativeLayout documentation
setBackgroundResource(0)
is the best option. From the documentation:
Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.
It works everywhere, because it's since API 1.
setBackground
was added much later, in API 16, so it will not work if your minSdkVersion
is lower than 16.
This helped me remove background color, hope it helps someone.
setBackgroundColor(Color.TRANSPARENT)
Try this code:
imgView.setImageResource(android.R.color.transparent);
also this one works:
imgView.setImageResource(0);
but be careful this one doesn't work:
imgView.setImageResource(null);
I try this code in android 4+:
view.setBackgroundDrawable(0);
Best performance on this method :
imageview.setBackgroundResource(R.drawable.location_light_green);
Use this.
In addition to the excellent answers, if you want to achieve this via xml then you can add:
android:background="@android:color/transparent
to your view.
This work for me:
yourview.setBackground(null);
Use setBackgroundColor(Color.TRANSPARENT)
to set the background as transparent, or use setBackgroundColor(0)
. Here Color.TRANSPARENT
is the default attribute from color class. It will work fine.
I have a case scenario and I tried all the answers from above, but always new image was created on top of the old one. The solution that worked for me is:
imageView.setImageResource(R.drawable.image);
First, you have to write in XML layout:
android:visibility="invisible" <!--or set VISIBLE-->
then use this to show it using Java:
myimage.setVisibility(SHOW); //HIDE
精彩评论