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

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

    For all the Kotlin users out there:

    context?.let {
        val color = ContextCompat.getColor(it, R.color.colorPrimary)
        // ...
    }
    
    0 讨论(0)
  • 2020-11-22 13:24

    If you don't necessarily need the resources, use parseColor(String):
    Color.parseColor("#cc0066")

    0 讨论(0)
  • 2020-11-22 13:27

    In Kotlin, you can do:

    ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)
    

    if requireContext() is accessible from where you are calling the function. I was getting an error when trying

    ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 13:29

    In Your RecyclerView in Kotlin

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
            textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
            textViewcolor.text = t.name
        }
    }
    
    0 讨论(0)
提交回复
热议问题