• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 com.android.tools.idea.validator.hierarchy;
18 
19 import com.android.ide.common.rendering.api.LayoutlibCallback;
20 
21 import android.view.View;
22 import android.widget.Checkable;
23 
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 
27 /** Helper for support lib dependencies. */
28 public class CustomHierarchyHelper {
29     public static LayoutlibCallback sLayoutlibCallback;
30 
31     /** Get the class instance from the studio based on the string class name. */
getClassByName(String className)32     public static Class<?> getClassByName(String className) {
33         try {
34             return sLayoutlibCallback.findClass(className);
35         } catch (ClassNotFoundException ignore) {
36         }
37         return null;
38     }
39 
40     /** Returns true if the view is of {@link Checkable} instance. False otherwise. */
isCheckable(View fromView)41     public static boolean isCheckable(View fromView) {
42         LayoutlibCallback callback = sLayoutlibCallback;
43         if (callback == null) {
44             return false;
45         }
46 
47         try {
48             // This is required as layoutlib does not know the support library such as
49             // MaterialButton. LayoutlibCallback calls for studio which understands all the maven
50             // pulled library.
51             Class button = callback.findClass(
52                     "com.google.android.material.button.MaterialButton");
53             if (button.isInstance(fromView)) {
54                 Method isCheckable = button.getMethod("isCheckable");
55                 Object toReturn = isCheckable.invoke(fromView);
56                 return (toReturn instanceof Boolean) && ((Boolean) toReturn);
57             }
58         } catch (ClassNotFoundException |
59                  NoSuchMethodException |
60                  IllegalAccessException |
61                  InvocationTargetException ignore) {
62         }
63         return fromView instanceof Checkable;
64     }
65 }
66