【问题标题】:removing backgroundcolor of a view in android在android中删除视图的背景色
【发布时间】:2011-05-02 08:22:13
【问题描述】:

在 Android 中移除背景颜色

我在这样的代码中设置了backgroundColor

View.setBackgroundColor(0xFFFF0000);

如何去除某些事件的背景色?

【问题讨论】:

  • 您可以将其设置为透明:View.setBackgroundColor(0x00000000);或 android.R.color.transparent
  • 刚刚发现,将其设置为透明的另一种方法是 View.setBackgroundColor(Color.TRANSPARENT);
  • 如果只想使用父母的背景,可以删除整个孩子的背景:view.setBackgroundResource(0);
  • 不适合我 toolbar.setBackgroundColor(Color.TRANSPARENT); @sat 不适合我 toolbar.setBackgroundColor(0);还有 View.setBackgroundColor(0x00000000);不适合我

标签: android background-color


【解决方案1】:

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

view.setBackgroundColor(0x00000000);

【讨论】:

  • 好的,我想会有一些东西可以移除 backgroundcolor 属性。
  • 因为它是一个 int 我不认为你可以把它“空”出来,这个答案应该也适用于 0x00AAF890 (或任何 0x00------),因为前两个0 将不透明度设置为 0%,即没有背景色。
【解决方案2】:

你可以使用

View.setBackgroundColor(Color.TRANSPARENT);

View.setBackgroundColor(0);

请记住,屏幕上几乎所有可见的东西都扩展了 View,比如 Button、TextView、ImageView、任何类型的 Layout 等等......

【讨论】:

  • Color.TRANSPARENT 看起来比 0x0000000 干净得多。你有我的赞成票!
【解决方案3】:

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

  1. 你最终会得到overdraw
  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));
    }
}

颜色int 只是转换为ColorDrawable,然后传递给setBackground(Drawable drawable)。因此,删除背景颜色的解决方案是通过以下方式将背景清空:

myView.setBackground(null);

【讨论】:

  • 这是合适的答案。使背景透明需要处理时间,而移除背景则不需要。
  • setBackground 来自 API 16,我该如何为较低的 API 做到这一点?
  • 对于较低的 api,您应该使用 myView.setBackgroundColor(Color.TRANSPARENT);
  • 这应该被接受,因为透明背景有隐藏的成本
【解决方案4】:

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

【讨论】:

    【解决方案5】:

    选择任何一个

    View.setBackgroundColor(Color.TRANSPARENT);
    
        or
    
        View.setBackgroundColor(0x00000000);
    

    【讨论】:

    • 这如何添加到现有答案中?
    猜你喜欢
    • 2015-03-02
    • 2016-08-06
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2010-11-02
    相关资源
    最近更新 更多