在android中删除视图的backgroundcolor

sat*_*sat 31 android background-color

在Android中删除背景颜色

我已经设置backgroundColor了这样的代码,

View.setBackgroundColor(0xFFFF0000);
Run Code Online (Sandbox Code Playgroud)

如何在某些事件中删除此背景颜色?

kik*_*iki 45

您应该尝试将背景颜色设置为透明:

view.setBackgroundColor(0x00000000);


小智 35

您可以使用

View.setBackgroundColor(Color.TRANSPARENT);

要么

View.setBackgroundColor(0);

请记住,屏幕上几乎所有可见的内容都会扩展View,如Button,TextView,ImageView,任何类型的布局等......

  • Color.TRANSPARENT看起来比0x0000000更清晰.你有我的upvote! (3认同)

The*_*rga 6

View.setBackgroundColor(0);也有效。没有必要把所有这些零。


tir*_*r38 6

有关将颜色设置为透明的所有答案都将在技术上起作用。但是这些方法存在两个问题:

  1. 您最终会透支
  2. 有一个更好的方法:

如果您查看View.setBackgroundColor(int color)工作原理,将会看到一个非常简单的解决方案:

/**
 * 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

颜色int仅转换为a ColorDrawable,然后传递给setBackground(Drawable drawable)。因此,消除背景色的解决方案是使用以下方法消除背景色:

myView.setBackground(null);
Run Code Online (Sandbox Code Playgroud)