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.deskclock 18 19 import android.content.Context 20 import android.content.res.TypedArray 21 import android.graphics.Color 22 import android.graphics.drawable.Drawable 23 import androidx.annotation.AttrRes 24 import androidx.annotation.ColorInt 25 26 object ThemeUtils { 27 /** Temporary array used internally to resolve attributes. */ 28 private val TEMP_ATTR = IntArray(1) 29 30 /** 31 * Convenience method for retrieving a themed color value. 32 * 33 * @param context the [Context] to resolve the theme attribute against 34 * @param attr the attribute corresponding to the color to resolve 35 * @return the color value of the resolved attribute 36 */ 37 @ColorInt resolveColornull38 fun resolveColor(context: Context, @AttrRes attr: Int): Int = 39 resolveColor(context, attr, stateSet = null) 40 41 /** 42 * Convenience method for retrieving a themed color value. 43 * 44 * @param context the [Context] to resolve the theme attribute against 45 * @param attr the attribute corresponding to the color to resolve 46 * @param stateSet an array of [android.view.View] states 47 * @return the color value of the resolved attribute 48 */ 49 @JvmStatic 50 @ColorInt 51 fun resolveColor(context: Context, @AttrRes attr: Int, @AttrRes stateSet: IntArray?): Int { 52 var a: TypedArray 53 synchronized(TEMP_ATTR) { 54 TEMP_ATTR[0] = attr 55 a = context.obtainStyledAttributes(TEMP_ATTR) 56 } 57 58 try { 59 if (stateSet == null) { 60 return a.getColor(0, Color.RED) 61 } 62 val colorStateList = a.getColorStateList(0) 63 return colorStateList?.getColorForState(stateSet, Color.RED) ?: Color.RED 64 } finally { 65 a.recycle() 66 } 67 } 68 69 /** 70 * Convenience method for retrieving a themed drawable. 71 * 72 * @param context the [Context] to resolve the theme attribute against 73 * @param attr the attribute corresponding to the drawable to resolve 74 * @return the drawable of the resolved attribute 75 */ 76 @JvmStatic resolveDrawablenull77 fun resolveDrawable(context: Context, @AttrRes attr: Int): Drawable? { 78 var a: TypedArray 79 synchronized(TEMP_ATTR) { 80 TEMP_ATTR[0] = attr 81 a = context.obtainStyledAttributes(TEMP_ATTR) 82 } 83 84 return try { 85 a.getDrawable(0) 86 } finally { 87 a.recycle() 88 } 89 } 90 }