Home » Android » layout – Remove background drawable programmatically in Android

layout – Remove background drawable programmatically in Android

Posted by: admin March 11, 2020 Leave a comment

Questions:

I want to remove the background drawable @drawable/bg programmatically.
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>
How to&Answers:

Try this

RelativeLayout relative = (RelativeLayout) findViewById(R.id.widget29);
relative.setBackgroundResource(0);

Check the setBackground functions in the RelativeLayout documentation

Answer:

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.

Answer:

This helped me remove background color, hope it helps someone.
setBackgroundColor(Color.TRANSPARENT)

Answer:

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); 

Answer:

I try this code in android 4+:

view.setBackgroundDrawable(0);

Answer:

Best performance on this method :

imageview.setBackgroundResource(R.drawable.location_light_green);

Use this.

Answer:

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.

Answer:

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);

Answer:

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.

Answer:

This work for me:

yourview.setBackground(null);

Answer:

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