开发者

removing backgroundcolor of a view in android

开发者 https://www.devze.com 2023-01-22 18:24 出处:网络
Removing Background co开发者_运维百科lor in Android I have set backgroundColor in code like this,

Removing Background co开发者_运维百科lor in Android

I have set backgroundColor in code like this,

View.setBackgroundColor(0xFFFF0000);

How to remove this background color on some event?


You should try setting the background color to transparent:

view.setBackgroundColor(0x00000000);


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


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


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


Choose Any one

View.setBackgroundColor(Color.TRANSPARENT);

    or

    View.setBackgroundColor(0x00000000);
0

精彩评论

暂无评论...
验证码 换一张
取 消