1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.support.v7.widget;
18 
19 import android.content.Context;
20 import android.content.res.Resources;
21 import android.graphics.drawable.Drawable;
22 import android.os.Build;
23 import android.support.annotation.NonNull;
24 import android.support.v7.app.AppCompatDelegate;
25 
26 import java.lang.ref.WeakReference;
27 
28 /**
29  * This class allows us to intercept calls so that we can tint resources (if applicable), and
30  * inflate vector resources from within drawable containers pre-L.
31  *
32  * @hide
33  */
34 public class VectorEnabledTintResources extends Resources {
35 
shouldBeUsed()36     public static boolean shouldBeUsed() {
37         return AppCompatDelegate.isCompatVectorFromResourcesEnabled()
38                 && Build.VERSION.SDK_INT <= MAX_SDK_WHERE_REQUIRED;
39     }
40 
41     /**
42      * The maximum API level where this class is needed.
43      */
44     public static final int MAX_SDK_WHERE_REQUIRED = 20;
45 
46     private final WeakReference<Context> mContextRef;
47 
VectorEnabledTintResources(@onNull final Context context, @NonNull final Resources res)48     public VectorEnabledTintResources(@NonNull final Context context,
49             @NonNull final Resources res) {
50         super(res.getAssets(), res.getDisplayMetrics(), res.getConfiguration());
51         mContextRef = new WeakReference<>(context);
52     }
53 
54     /**
55      * We intercept this call so that we tint the result (if applicable). This is needed for
56      * things like {@link android.graphics.drawable.DrawableContainer}s which can retrieve
57      * their children via this method.
58      */
59     @Override
getDrawable(int id)60     public Drawable getDrawable(int id) throws NotFoundException {
61         final Context context = mContextRef.get();
62         if (context != null) {
63             return AppCompatDrawableManager.get().onDrawableLoadedFromResources(context, this, id);
64         } else {
65             return super.getDrawable(id);
66         }
67     }
68 
superGetDrawable(int id)69     final Drawable superGetDrawable(int id) {
70         return super.getDrawable(id);
71     }
72 }