ResourcesCompat.getDrawable() vs AppCompatResources.getDrawable()

后端 未结 4 1740
醉话见心
醉话见心 2021-01-30 08:45

I\'m a bit confused with these two APIs.

ResourcesCompat.getDrawable(Resources res, int id, Resources.Theme theme)

Return a drawable

4条回答
  •  轮回少年
    2021-01-30 09:39

    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);
    

提交回复
热议问题