• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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.graphics.drawable;
18 
19 import com.android.layoutlib.bridge.impl.RenderAction;
20 import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
21 
22 import android.util.LruCache;
23 import android.view.InflateException;
24 
25 import java.lang.reflect.Constructor;
26 
27 public class DrawableInflater_Delegate {
28     private static final LruCache<String, Constructor<? extends Drawable>> CONSTRUCTOR_MAP =
29             new LruCache<>(20);
30 
31     /**
32      * This is identical to the original method except that it uses LayoutlibCallback to
33      * load the drawable class, which enables loading custom drawables from the project.
34      */
35     @LayoutlibDelegate
inflateFromClass(DrawableInflater thisInflater, String className)36     /* package */ static Drawable inflateFromClass(DrawableInflater thisInflater,
37             String className) {
38         try {
39             Constructor<? extends Drawable> constructor;
40             synchronized (CONSTRUCTOR_MAP) {
41                 constructor = CONSTRUCTOR_MAP.get(className);
42                 if (constructor == null) {
43                     final Class<? extends Drawable> clazz =
44                             RenderAction.getCurrentContext().getLayoutlibCallback()
45                                     .findClass(className).asSubclass(Drawable.class);
46                     constructor = clazz.getConstructor();
47                     CONSTRUCTOR_MAP.put(className, constructor);
48                 }
49             }
50             return constructor.newInstance();
51         } catch (ClassCastException e) {
52             // If loaded class is not a Drawable subclass.
53             throw new InflateException("Class is not a Drawable " + className, e);
54         } catch (ClassNotFoundException e) {
55             // If loadClass fails, we should propagate the exception.
56             throw new InflateException("Class not found " + className, e);
57         } catch (Exception e) {
58             throw new InflateException("Error inflating class " + className, e);
59         }
60     }
61 
clearConstructorCache()62     public static void clearConstructorCache() {
63         CONSTRUCTOR_MAP.evictAll();
64     }
65 }
66