sat
sat

Reputation: 41076

removing backgroundcolor of a view in android

Removing Background color in Android

I have set backgroundColor in code like this,

View.setBackgroundColor(0xFFFF0000);

How to remove this background color on some event?

Upvotes: 48

Views: 51855

Answers (5)

Zeus
Zeus

Reputation: 616

You can use

View.setBackgroundColor(Color.TRANSPARENT);

or

View.setBackgroundColor(0);

or even

View.setBackground(null);

Please remember that almost everything visible on the screen extends View, like a Button, TextView, ImageView, any kind of Layout, so this can be done to almost everything.

Bonus point!

Instead of using View.setBackgroundColor(0xFFFF0000); it is sooooooooo much better to create a color filter with android.graphics.PorterDuff.MULTIPLY option and, if needed, just clear the filter.

Using the color filter, colors look much better because it won't be that "flat" color but a nicer tone of the chosen color.

A light red background would be View.getBackground().setColorFilter(0x3FFF0000, PorterDuff.Mode.MULTIPLY);

To "remove" the color, just use View.getBackground().clearColorFilter();

Upvotes: 51

dileep krishnan
dileep krishnan

Reputation: 344

Choose Any one

View.setBackgroundColor(Color.TRANSPARENT);

    or

    View.setBackgroundColor(0x00000000);

Upvotes: 0

tir38
tir38

Reputation: 10421

All of the answers about setting color to transparent will work technically. But there are two problems with these approaches:

  1. You'll end up with overdraw.
  2. There is a better way:

If you look at how View.setBackgroundColor(int color) works you'll see a pretty easy solution:

/**
 * Sets the background color for this view.
 * @param color the color of the background
 */
@RemotableViewMethod
public void setBackgroundColor(@ColorInt int color) {
    if (mBackground instanceof ColorDrawable) {
        ((ColorDrawable) mBackground.mutate()).setColor(color);
        computeOpaqueFlags();
        mBackgroundResource = 0;
    } else {
        setBackground(new ColorDrawable(color));
    }
}

The color int is just converted to a ColorDrawable and then passed to setBackground(Drawable drawable). So the solution to remove background color is to just null out the background with:

myView.setBackground(null);

Upvotes: 17

kiki
kiki

Reputation: 13997

You should try setting the background color to transparent:

view.setBackgroundColor(0x00000000);

Upvotes: 61

DN2048
DN2048

Reputation: 3804

View.setBackgroundColor(0); also works. It isn't necessary to put all those zeros.

Upvotes: 6

Related Questions