Android开发

获取color资源色值

2021-11-25  本文已影响0人  卓技卓品

为了实现应用切换主题(日常模式、夜间模式)时,应用内各种组件的显示效果也能很友好的切换。所以在应用内所使用的color色值尽量使用values内colors.xml资源文件内。 这样的好处显而易见:需要调整效果时,无效代码内到处检查,直接在文件内配置即可;可以给不同的主题设置不同的色值等等。 但是使用时在细节上遇到一些问题,有部分View是使用代码进行绘制,比如项目(sleepassistant为例)中,折线图、扇形图等图形及日历使用Java代码进行绘制。这时候如何给画笔配置color.xml内定义的资源呢? 在旧版本系统中,我们可以使用下面的方式:

int tickLabelColor = getResources().getColor(R.color.tick_label_color);

但是系统提示该方法已过时:

Returns a color integer associated with a particular resource ID. If the resource holds a complex ColorStateList, then the default color from the set is returned.
Deprecated:Use getColor(int, Resources.Theme) instead.

翻译:

返回与特定资源 ID 关联的颜色整数。如果资源拥有复杂的 ColorStateList,则返回集合中的默认颜色。
已弃用:使用 getColor(int, Resources.Theme) 代替。

其中 Resources.Theme可为null,为null时获取当前手机主题模式下的color resource ID。 新方式实现如下:

int tickLabelColor = getResources().getColor(R.color.tick_label_color, null);

我们查看源码发现getResources方式是Context定义的抽象方法。为了更好的访问 Context 中的功能,Android系统引入了ContextCompat,查询ContextCompat发现有一个静态方法getColor,查看代码:

@ColorInt
public static final int getColor(Context context, @ColorRes int id) {
    if (Build.VERSION.SDK_INT >= 23) {
        return context.getColor(id);
    } else {
        return context.getResources().getColor(id);
    }
}

该方法对API 23版本进行了兼容,对于低于23的系统,其实调用的还是Context中的getColor。因此我们也可以使用:

int tickLabelColor = ContextCompat.getColor(this, R.color.tick_label_color);

获取到color id后,可以通过setColor进行设置:

Paint paint = new Paint();
int tickLabelColor = ContextCompat.getColor(getContext(), R.color.tick_label_color);
paint.setColor(tickLabelColor);

与getColor 对应的,getDrawable 用法也是一样。

// 弃用方法
Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
// 建议方法
Drawable drawable1 = getResources().getDrawable(R.mipmap.ic_launcher, null);
Drawable drawable2 = ContextCompat.getDrawable(this,R.mipmap.ic_launcher);

代码效果参考睡眠助理项目。

上一篇 下一篇

猜你喜欢

热点阅读