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

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

    If your current min. API level is 23, you can simply use getColor() like we are using to get string resources by getString():

    //example
    textView.setTextColor(getColor(R.color.green));
    // if `Context` is not available, use with context.getColor()
    

    You can constraint for API Levels below 23:

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

    but to keep it simple, you can do like below as accepted answer:

    textView.setTextColor(ContextCompat.getColor(context, R.color.green))
    

    From Resources.

    From ContextCompat AndroidX.

    From ContextCompat Support

提交回复
热议问题