With new android API 22 getResources().getDrawable()
is now deprecated.
Now the best approach is to use only getDrawable()
.
What changed? <
getDrawable(int drawable) is deprecated in API level 22. For reference see this link.
Now to resolve this problem we have to pass a new constructer along with id like as :-
getDrawable(int id, Resources.Theme theme)
For Solutions Do like this:-
In Java:-
ContextCompat.getDrawable(getActivity(), R.drawable.name);
or
imgProfile.setImageDrawable(getResources().getDrawable(R.drawable.img_prof, getApplicationContext().getTheme()));
In Kotlin :-
rel_week.background=ContextCompat.getDrawable(this.requireContext(), R.color.colorWhite)
or
rel_day.background=resources.getDrawable(R.drawable.ic_home, context?.theme)
Hope this will help you.Thanks.
Try this:
public static List<ProductActivity> getCatalog(Resources res){
if(catalog == null) {
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.product_salmon),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.switchbook),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.watchmen),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
}
en api level 14
marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));
You have some options to handle this deprecation the right (and future proof) way, depending on which kind of drawable you are loading:
A) drawables with theme attributes
ContextCompat.getDrawable(getActivity(), R.drawable.name);
You'll obtain a styled Drawable as your Activity theme instructs. This is probably what you need.
B) drawables without theme attributes
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
You'll get your unstyled drawable the old way. Please note: ResourcesCompat.getDrawable()
is not deprecated!
EXTRA) drawables with theme attributes from another theme
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
You can use
ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);
that's work for me
For some who still got this issue to solve even after applying the suggestion of this thread(i used to be one like that) add this line on your Application class, onCreate() method
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
As suggested here and here sometimes this is required to access vectors from resources especially when you're dealing with menu items, etc