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

前端 未结 11 1960
我寻月下人不归
我寻月下人不归 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:29

    I don't want to include the Support library just for getColor, so I'm using something like

    public static int getColorWrapper(Context context, int id) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return context.getColor(id);
        } else {
            //noinspection deprecation
            return context.getResources().getColor(id);
        }
    }
    

    I guess the code should work just fine, and the deprecated getColor cannot disappear from API < 23.

    And this is what I'm using in Kotlin:

    /**
     * Returns a color associated with a particular resource ID.
     *
     * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
     */
    @Suppress("DEPRECATION")
    @ColorInt
    fun getColorHelper(context: Context, @ColorRes id: Int) =
        if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);
    

提交回复
热议问题