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.content.res.ColorStateList; 20import android.graphics.Color; 21import android.graphics.PorterDuff; 22import android.graphics.PorterDuffColorFilter; 23import android.graphics.drawable.Drawable; 24 25/** 26 * A {@link DrawableWrapper} which updates it's color filter using a {@link ColorStateList}. 27 */ 28class TintDrawableWrapper extends DrawableWrapper { 29 30 private final ColorStateList mTintStateList; 31 private final PorterDuff.Mode mTintMode; 32 33 private int mCurrentColor; 34 35 public TintDrawableWrapper(Drawable drawable, ColorStateList tintStateList) { 36 this(drawable, tintStateList, TintManager.DEFAULT_MODE); 37 } 38 39 public TintDrawableWrapper(Drawable drawable, ColorStateList tintStateList, 40 PorterDuff.Mode tintMode) { 41 super(drawable); 42 mTintStateList = tintStateList; 43 mTintMode = tintMode; 44 } 45 46 @Override 47 public boolean isStateful() { 48 return (mTintStateList != null && mTintStateList.isStateful()) || super.isStateful(); 49 } 50 51 @Override 52 public boolean setState(int[] stateSet) { 53 boolean handled = super.setState(stateSet); 54 handled = updateTint(stateSet) || handled; 55 return handled; 56 } 57 58 private boolean updateTint(int[] state) { 59 if (mTintStateList != null) { 60 final int color = mTintStateList.getColorForState(state, mCurrentColor); 61 if (color != mCurrentColor) { 62 if (color != Color.TRANSPARENT) { 63 setColorFilter(color, mTintMode); 64 } else { 65 clearColorFilter(); 66 } 67 mCurrentColor = color; 68 return true; 69 } 70 } 71 return false; 72 } 73 74} 75