The Resources.getColor(int id)
method has been deprecated.
@ColorInt
@Deprecated
public int getColor(@ColorRes int id) throws NotFoundException
For all the Kotlin users out there:
context?.let {
val color = ContextCompat.getColor(it, R.color.colorPrimary)
// ...
}
If you don't necessarily need the resources, use parseColor(String):
Color.parseColor("#cc0066")
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)
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);
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
}
}