Using:
buildToolsVersion "22.0.1"
,
targetSdkVersion 22
in my gradle file.
I found that the useful getResources().getColor(R.color.color_name)
is deprecated.
What should I use instead?
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
It looks like the best approach is to use:
ContextCompat.getColor(context, R.color.color_name)
eg:
yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
R.color.colorAccent))
This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.
You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).
ContextCompat.getColor(context, R.color.my_color)
As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.
You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:
compile 'com.android.support:support-v4:23.0.1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With