getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

前端 未结 11 1996
我寻月下人不归
我寻月下人不归 2020-11-22 12:29

The Resources.getColor(int id) method has been deprecated.

@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException          


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 13:05

    I got frustrated too. My need was very straightforward. All I wanted was the ARGB color from the resources, so I wrote a simple static method.

    protected static int getARGBColor(Context c, int resId)
            throws Resources.NotFoundException {
    
        TypedValue color = new TypedValue();
        try {
            c.getResources().getValue(resId, color, true);
        }
        catch (Resources.NotFoundException e) {
            throw(new Resources.NotFoundException(
                      String.format("Failed to find color for resourse id 0x%08x",
                                    resId)));
        }
        if (color.type != TYPE_INT_COLOR_ARGB8) {
            throw(new Resources.NotFoundException(
                      String.format(
                          "Resourse id 0x%08x is of type 0x%02d. Expected TYPE_INT_COLOR_ARGB8",
                          resId, color.type))
            );
        }
        return color.data;
    }
    

提交回复
热议问题