【问题标题】:How can I get color-int from color resource?如何从颜色资源中获取 color-int?
【发布时间】:2011-07-13 09:14:42
【问题描述】:

有没有办法从颜色资源中获取 color-int?

我正在尝试获取资源 (R.color.myColor) 中定义的颜色的单个红色、蓝色和绿色分量,以便我可以将三个搜索栏的值设置为特定级别。

【问题讨论】:

    标签: android colors android-resources


    【解决方案1】:

    你可以使用:

    getResources().getColor(R.color.idname);
    

    在此处查看如何定义自定义颜色:

    http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

    编辑(1): 由于getColor(int id) 现在已弃用,因此必须使用它:

    ContextCompat.getColor(context, R.color.your_color);
    

    (在支持库 23 中添加)

    编辑(2):

    以下代码可用于棉花糖前后 (API 23)

    ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme
    
    ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme
    

    【讨论】:

    • android.R.color.some_color 怎么样 :-(
    • @Blundell 呃,不知道你现在是否需要它,但这也适用于android.R.color.some_color,例如:getResources().getColor(android.R.color.holo_blue_bright)(至少在 API 17 上)
    • getColor() 现已弃用,您可以使用:ContextCompat.getColor(context, R.color.your_color);
    • 为什么 Google 觉得有必要为那个糟糕的应用程序紧凑库弃用一个完美的功能。太烂了,两个都有。
    • 我永远敬畏这个平台的残暴......无言以对。
    【解决方案2】:

    定义你的颜色

    values/color.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <!-- color int as #AARRGGBB (alpha, red, green, blue) -->
        <color name="orange">#fff3632b</color>
        ...
        <color name="my_view_color">@color/orange</color>
    
    </resources>
    

    获取颜色 int 并设置

    int backgroundColor = ContextCompat.getColor(context, R.color.my_view_color);
    // Color backgroundColor = ... (Don't do this. The color is just an int.)
    
    myView.setBackgroundColor(backgroundColor);
    

    另见

    【讨论】:

    • 你只能在ActivityFragment 中使用getResources() 吗?
    • @Zapnologica,有关在 Activity 或 Fragment 之外使用 getResources() 的想法,请参阅this question 的答案。
    • @Zapnologica 没有。 getResources() 也可作为公共 API 用于任何实现 Context 和 Views 的东西。
    【解决方案3】:

    基于新的 Android 支持库(和 this 更新),现在您应该调用:

    ContextCompat.getColor(context, R.color.name.color);
    

    根据documentation

    public int getColor (int id)
    

    此方法已在 API 级别 23 中弃用。 改用 getColor(int, Theme)

    getResources().getColorStateList(id)也是一样的解决方案:

    你必须像这样改变它:

    ContextCompat.getColorStateList(getContext(),id);
    

    编辑 2019

    关于ThemeOverlay使用最近视图的上下文:

    val color = ContextCompat.getColor(
      closestView.context,
      R.color.name.color
    )
    

    因此,您可以根据 ThemeOverlay 获得正确的颜色。

    在同一活动中使用不同主题时特别需要,例如深色/浅色主题。如果您想了解更多关于主题和样式的信息,建议您参加此讲座:Developing Themes with Style

    【讨论】:

    • 对于那些想在新方法中填写什么作为主题的人,Theme 可以作为 null 传递,所以如果您不确定要传递什么主题,只需调用 getColor(R.color.my_color, null)
    • 嗯......这是每个人都说的,但我无法让它工作。我必须初始化上下文吗?目前我得到“无法解析符号'上下文'”
    • 为了确保你做对了,尝试在活动的 onCreate 中调用它,而不是获取上下文你需要调用 getContext() 或者只是“this”
    【解决方案4】:

    我更新为使用 ContextCompat.getColor(context, R.color.your_color);,但有时(在某些设备/Android 版本上。我不确定)会导致 NullPointerExcepiton。

    因此,为了使其适用于所有设备/版本,在空指针的情况下,我会使用旧的方法。

    try {
        textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
    }
    catch(NullPointerException e) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
        }
        else {
            textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
        }
    }
    

    【讨论】:

    • 为什么不在所有情况下都使用旧版本,或者如果您仍然在检查版本,请尽可能使用新 API Resources.getColor(int, Theme)?您不应该捕获运行时异常。
    • 我想只是强迫症。 ContextCompat,对我来说似乎是未来的证明方式,因此是正确的方式。所以我的方法是,以正确的方式去做。如果失败(在旧设备或其他设备上),请以旧方式进行。为什么我不应该在运行时捕获异常?
    【解决方案5】:

    最佳方法

    作为@sat 的回答,获取颜色的好方法是

    ResourcesCompat.getColor(getResources(), R.color.your_color, null);
    

    当您无权访问getResources() 方法时,请使用以下方式。

    Context context  = getContext(); // like Dialog class
    ResourcesCompat.getColor(context.getResources(), R.color.your_color, null);
    

    我做的是

    public void someMethod(){
        ...
        ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
    }
    

    在您的应用程序中的任何地方使用都是最简单的!即使在 Util 类或任何没有 Context 或 getResource() 的类中

    问题(当你没有上下文时)

    您没有Context 访问权限时,例如您的Util 类中的方法。

    假设下面的方法没有上下文。

    public void someMethod(){
        ...
        // can't use getResource() without Context.
    }
    

    现在您将在此方法中将Context 作为参数传递并使用getResources().

    public void someMethod(Context context){
        ...
        context.getResources...
    }
    

    所以这是一个独特的解决方案,您可以通过它从任何地方访问资源,例如 Util class 。 将Resources 添加到您的Application 类中,如果不存在则创建一个。

    import android.app.Application;
    import android.content.res.Resources;
    
    public class App extends Application {
        private static App mInstance;
        private static Resources res;
    
    
        @Override
        public void onCreate() {
            super.onCreate();
            mInstance = this;
            res = getResources();
        }
    
        public static App getInstance() {
            return mInstance;
        }
    
        public static Resources getResourses() {
            return res;
        }
    
    }
    

    将名称字段添加到您的 manifest.xml &lt;application 标记。 (如果尚未添加)

    <application
            android:name=".App"
            ...
            >
            ...
        </application>
    

    现在你可以走了。在应用中的任何位置使用ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);

    【讨论】:

      【解决方案6】:

      从非活动类访问颜色可能很困难。我发现的替代方法之一是使用enumenum 提供了很大的灵活性。

      public enum Colors
      {
        COLOR0(0x26, 0x32, 0x38),    // R, G, B
        COLOR1(0xD8, 0x1B, 0x60),
        COLOR2(0xFF, 0xFF, 0x72),
        COLOR3(0x64, 0xDD, 0x17);
      
      
        private final int R;
        private final int G;
        private final int B;
      
        Colors(final int R, final int G, final int B)
        {
          this.R = R;
          this.G = G;
          this.B = B;
        }
      
        public int getColor()
        {
          return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
        }
      
        public int getR()
        {
          return R;
        }
      
        public int getG()
        {
          return G;
        }
      
        public int getB()
        {
          return B;
        }
      }
      

      【讨论】:

        【解决方案7】:
        ContextCompat.getColor(context, R.color.your_color);
        

        活动中

        ContextCompat.getColor(actvityname.this, R.color.your_color);
        

        在片段中

        ContextCompat.getColor(getActivity(), R.color.your_color);
        

        例如:

        tvsun.settextcolour(ContextCompat.getColor(getActivity(), R.color.your_color))
        

        【讨论】:

          【解决方案8】:

          有关可能有助于在搜索结果中显示此问题的另一个用例的更多信息,我想将 alpha 应用于我的资源中定义的颜色。

          使用@sat 的正确答案:

          int alpha = ... // 0-255, calculated based on some business logic
          int actionBarBackground = getResources().getColor(R.color.actionBarBackground);
          int actionBarBackgroundWithAlpha = Color.argb(
                  alpha,
                  Color.red(actionbarBackground),
                  Color.green(actionbarBackground),
                  Color.blue(actionbarBackground)
          );
          

          【讨论】:

            【解决方案9】:

            最近的工作方法:

            getColor(R.color.snackBarAction)
            

            【讨论】:

              【解决方案10】:

              如果您当前的最小值。 API 级别为 23,您可以像我们使用 getString() 一样简单地使用 getColor()

              //example
              textView.setTextColor(getColor(R.color.green));
              // if context is not available(ex: not in activity) use with context.getColor()
              

              如果你想要低于 API 级别 23,只需使用这个:

              textView.setTextColor(getResources().getColor(R.color.green));
              

              但请注意,getResources().getColor() 在 API 级别 23 中已弃用。在这种情况下,将上面替换为:

              textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`
              

              ContextCompat:访问Context中功能的助手

              如果您愿意,可以使用SDK_INT 进行约束,如下所示:

              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                  textView.setTextColor(getColor(R.color.green));
              } else {
                  textView.setTextColor(getResources().getColor(R.color.green));
              }
              

              【讨论】:

                【解决方案11】:

                找到了一种更简单的方法:

                Color.parseColor(getString(R.color.idname);
                

                【讨论】:

                • 有趣,没想到可以通过这种方式将颜色作为字符串获取。我不认为这更容易,但它很有趣?
                【解决方案12】:

                或者如果你有一个函数(字符串文本,字符串颜色)并且你需要传递资源颜色字符串,你可以这样做

                String.valueOf(getResources().getColor(R.color.enurse_link_color))
                

                【讨论】:

                  【解决方案13】:

                  在 kotlin 中,只需在您的活动中使用它

                  R.color.color_name
                  

                  前-

                  mytextView.setTextColor(R.color.red_900)
                  

                  【讨论】:

                  • 这不能回答问题。
                  • 收到警告Should pass resolved color instead of resource id here: getResources().getColor(R.color.Black)
                  猜你喜欢
                  • 2011-04-18
                  • 2012-10-31
                  • 1970-01-01
                  • 2011-05-09
                  • 2021-11-13
                  • 1970-01-01
                  • 2014-10-31
                  • 1970-01-01
                  • 2022-06-29
                  相关资源
                  最近更新 更多