【问题标题】:Background Color remains white regardless of settings无论设置如何,背景颜色都保持白色
【发布时间】:2014-04-07 05:58:50
【问题描述】:

我的应用有“深色背景”和“浅色背景”设置。深色背景使用 holo_dark png drawable,效果很好。但是,我希望浅色背景是在 g-mail 应用和其他谷歌应用中使用的灰色作为背景。

在我的 XML 布局图形视图中,默认值为适当的灰色,看起来不错。但是,在我的应用程序中,背景是白色的。我什至尝试过以编程方式设置它(不仅仅是通过 XML),它仍然显示为白色!

字符串.xml

<color name="grey">#d3d3d3</color>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/background"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/grey"
    tools:context=".MainActivity" >

MainActivity.java

    mBackground.setBackgroundColor(0xd3d3d3);

XML 视图 http://i.imgur.com/1vVNqTP.png

截图 http://i.imgur.com/ZadjpPi.png

在你说屏幕截图看起来是灰色之前,我将十六进制代码更改为 FF0000 (RED),它仍然是白色的!

我还从 XML 文件的布局中删除了背景属性,并且无法更改背景颜色。

【问题讨论】:

    标签: android user-interface layout


    【解决方案1】:

    使用这个:

    mBackground.setBackgroundColor(getResources().getColor(R.color.grey));
    

    在 values 文件夹中创建新的 color.xml,如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
            <color name="grey">#d3d3d3</color>
    </resources>
    

    【讨论】:

      【解决方案2】:

      使用时

      mBackground.setBackgroundColor(...);
      

      您可以传递来自 Color 类的整数值,也可以传递 包括 alpha 的十六进制值(例如,0xff000000 表示黑色)。

      如果你想从 XML 加载你的颜色,首先在values/ 文件夹中创建一个colors.xml 文件,如下所示:

      <?xml version="1.0" encoding="utf-8"?>
      <resources>
              <color name="grey">#d3d3d3</color>
      </resources>
      

      然后使用您的布局的background 属性引用它,您已经正确地这样做了。

      【讨论】:

      • 这与我已经在做的不同吗?您刚刚创建了一个 colors.xml 来添加我刚刚放入 strings.xml 的值。 (如上所示,这不起作用。)
      • 1.我帖子的第一部分是关于以编程方式设置颜色,但您没有正确执行。 2. 为什么不将颜色存储在colors.xml 而不是strings.xml?只需按照必须完成的方式去做,它就会起作用。就这么简单。
      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多