With new android API 22 getResources().getDrawable()
is now deprecated.
Now the best approach is to use only getDrawable()
.
What changed? <
Build.VERSION_CODES.LOLLIPOP should now be changed to BuildVersionCodes.Lollipop i.e:
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder, Context.Theme);
} else {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder);
}
Just an example of how I fixed the problem in an array to load a listView, hope it helps.
mItems = new ArrayList<ListViewItem>();
// Resources resources = getResources();
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));
In Kotlin you can use extension
fun Context.getMyDrawable(id : Int) : Drawable?{
return ContextCompat.getDrawable(this, id)
}
then use like
context.getMyDrawable(R.drawable.my_icon)
getDrawable (int id, Resources.Theme theme) (Added in API level 21)
This is an example:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
This is an example how to validate for later versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage));
}
Now you need to implement like this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
//
} else {
//
}
Following single line of code is enough, everything will take care by ContextCompat.getDrawable
ContextCompat.getDrawable(this, R.drawable.your_drawable_file)
If you are targeting SDK > 21 (lollipop or 5.0) use
context.getDrawable(R.drawable.your_drawable_name)
See docs