【问题标题】:How do I set color with .setBackgroundColor(); with color from values/colors.xml如何使用 .setBackgroundColor(); 设置颜色使用 values/colors.xml 中的颜色
【发布时间】:2018-04-21 15:37:53
【问题描述】:

在 Android 中,我尝试从 res/values/colors.xml 设置颜色

使用title.setBackgroundColor()

目前我可以设置为:title.setBackgroundColor(Color.GREEN);

但是,我想引用 .xml 中的颜色

当我使用时:

title.setBackgroundColor(R.color.white);

指:

<color name="white">#FFFFFF</color>

Andriod 工作室报告:

Should pass resolved color instead of resource id here: `getResources().getColor(R.color.white)` less... (⌘F1) 
This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations.  Examples of errors flagged by this inspection:
Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
Forgetting to invoke the overridden method (via super) in methods that require it
Calling a method that requires a permission without having declared that permission in the manifest
Passing a resource color reference to a method which expects an RGB integer value.
...and many more.  For more information, see the documentation at http://developer.android.com/tools/debugging/annotations.html

【问题讨论】:

标签: android android-layout android-color


【解决方案1】:

转到 res->values->color.xml 并编写如下代码:

colors.xml

<resources>
    <color name="name_color">#3F51B5</color>
</resources>

设置:

title.setBackgroundResource(R.color.name_color);

【讨论】:

    【解决方案2】:

    在您的 xml 文件中:

    <color name="newcolor">#FF00</color>
    

    并使用

    title.setBackgroundResource(R.color.newcolor);
    

    【讨论】:

      【解决方案3】:

      您需要使用ContextCompat.getColor(getContext(), R.color.green)。这将通过您传递的 ID 为您提供所需的颜色。最后:

      title.setBackgroundColor(ContextCompat.getColor(getContext, R.color.green));
      

      【讨论】:

        【解决方案4】:

        您可以在 Xamarin 中尝试

        SomeView.SetBackgroundResource(Resource.Color.justRed);
        

        【讨论】:

          【解决方案5】:

          添加这个

          title.setBackground(getResources().getColor(R.color.yourcolor));
          

          title.setBackgroundResource(R.color.yourColor);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-29
            • 2019-07-31
            • 2016-01-25
            • 1970-01-01
            • 2021-12-06
            • 2015-12-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多