1/* 2 * Copyright (C) 2014 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 17package android.support.v7.internal.widget; 18 19import android.annotation.TargetApi; 20import android.content.Context; 21import android.graphics.drawable.Drawable; 22import android.os.Build; 23import android.util.AttributeSet; 24import android.widget.ListPopupWindow; 25import android.widget.Spinner; 26 27import java.lang.reflect.Field; 28 29/** 30 * An tint aware {@link android.widget.Spinner}. 31 * 32 * @hide 33 */ 34public class TintSpinner extends Spinner { 35 36 private static final int[] TINT_ATTRS = { 37 android.R.attr.background, 38 android.R.attr.popupBackground 39 }; 40 41 public TintSpinner(Context context) { 42 this(context, null); 43 } 44 45 public TintSpinner(Context context, AttributeSet attrs) { 46 this(context, attrs, android.R.attr.spinnerStyle); 47 } 48 49 public TintSpinner(Context context, AttributeSet attrs, int defStyleAttr) { 50 super(context, attrs, defStyleAttr); 51 52 TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs, TINT_ATTRS, 53 defStyleAttr, 0); 54 setBackgroundDrawable(a.getDrawable(0)); 55 56 if (a.hasValue(1)) { 57 final Drawable background = a.getDrawable(1); 58 if (Build.VERSION.SDK_INT >= 16) { 59 setPopupBackgroundDrawable(background); 60 } else if (Build.VERSION.SDK_INT >= 11) { 61 setPopupBackgroundDrawableV11(this, background); 62 } 63 } 64 65 a.recycle(); 66 } 67 68 @TargetApi(Build.VERSION_CODES.HONEYCOMB) 69 private static void setPopupBackgroundDrawableV11(Spinner view, Drawable background) { 70 try { 71 Field popupField = Spinner.class.getDeclaredField("mPopup"); 72 popupField.setAccessible(true); 73 74 Object popup = popupField.get(view); 75 76 if (popup instanceof ListPopupWindow) { 77 ((ListPopupWindow) popup).setBackgroundDrawable(background); 78 } 79 } catch (NoSuchFieldException e) { 80 e.printStackTrace(); 81 } catch (IllegalAccessException e) { 82 e.printStackTrace(); 83 } 84 } 85 86} 87