Home | History | Annotate | Download | only in widget
      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.design.widget;
     18 
     19 import android.graphics.drawable.Drawable;
     20 import android.graphics.drawable.DrawableContainer;
     21 import android.util.Log;
     22 
     23 import java.lang.reflect.Method;
     24 
     25 /**
     26  * Caution. Gross hacks ahead.
     27  */
     28 class DrawableUtils {
     29 
     30     private static final String LOG_TAG = "DrawableUtils";
     31 
     32     private static Method sSetConstantStateMethod;
     33     private static boolean sSetConstantStateMethodFetched;
     34 
     35     private DrawableUtils() {}
     36 
     37     static boolean setContainerConstantState(DrawableContainer drawable,
     38             Drawable.ConstantState constantState) {
     39         // We can use getDeclaredMethod() on v9+
     40         return setContainerConstantStateV9(drawable, constantState);
     41     }
     42 
     43     private static boolean setContainerConstantStateV9(DrawableContainer drawable,
     44             Drawable.ConstantState constantState) {
     45         if (!sSetConstantStateMethodFetched) {
     46             try {
     47                 sSetConstantStateMethod = DrawableContainer.class.getDeclaredMethod(
     48                         "setConstantState", DrawableContainer.DrawableContainerState.class);
     49                 sSetConstantStateMethod.setAccessible(true);
     50             } catch (NoSuchMethodException e) {
     51                 Log.e(LOG_TAG, "Could not fetch setConstantState(). Oh well.");
     52             }
     53             sSetConstantStateMethodFetched = true;
     54         }
     55         if (sSetConstantStateMethod != null) {
     56             try {
     57                 sSetConstantStateMethod.invoke(drawable, constantState);
     58                 return true;
     59             } catch (Exception e) {
     60                 Log.e(LOG_TAG, "Could not invoke setConstantState(). Oh well.");
     61             }
     62         }
     63         return false;
     64     }
     65 }
     66