I\'m a bit confused with these two APIs.
ResourcesCompat.getDrawable(Resources res, int id, Resources.Theme theme)
Return a drawable
API 19+ workaround
package com.example;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
/**
* https://stackoverflow.com/a/48237058/1046909
*/
public class AppDrawableCompat {
public static Drawable getDrawable(@NonNull Context context, @DrawableRes int resId) {
try {
return AppCompatResources.getDrawable(context, resId);
} catch (Resources.NotFoundException e1) {
try {
return ContextCompat.getDrawable(context, resId);
} catch (Resources.NotFoundException e2) {
return VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
}
}
}
@Nullable
public static Drawable findDrawable (@NonNull Context context, @DrawableRes int resId) {
try {
return getDrawable(context, resId);
} catch (Resources.NotFoundException e) {
return null;
}
}
public static void setViewBackgroundDrawable(@NonNull View view, @NonNull Context context, @DrawableRes int resId) {
Drawable drawable = findDrawable(context, resId);
if (drawable != null) {
view.setBackground(drawable);
}
}
}
Using example (MainActivity#onCreate)
ImageView icon = findViewById(R.id.icon);
AppDrawableCompat.setViewBackgroundDrawable(icon, this, R.drawable.bg_icon);