1 /** 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * ``` 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * ``` 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 package com.android.healthconnect.controller.utils 15 16 import android.content.Context 17 import android.content.res.Resources 18 import android.graphics.drawable.Drawable 19 import android.util.TypedValue 20 import androidx.annotation.AttrRes 21 import androidx.appcompat.content.res.AppCompatResources 22 23 /** Utility class for resoling attribute references in the theme. */ 24 object AttributeResolver { getDrawablenull25 fun getDrawable(context: Context, @AttrRes attribute: Int): Drawable? { 26 return AppCompatResources.getDrawable(context, getResource(context, attribute)) 27 } 28 getNullableDrawablenull29 fun getNullableDrawable(context: Context, @AttrRes attribute: Int): Drawable? { 30 if (!(hasAttribute(context, attribute))) { 31 return null 32 } 33 val resourceId = getResource(context, attribute) 34 if (resourceId == Resources.ID_NULL) { 35 return null 36 } 37 return AppCompatResources.getDrawable(context, resourceId) 38 } getResourcenull39 fun getResource(context: Context, @AttrRes attribute: Int): Int { 40 val outValue = TypedValue() 41 check(context.theme.resolveAttribute(attribute, outValue, true)) 42 return outValue.resourceId 43 } hasAttributenull44 fun hasAttribute(context: Context, @AttrRes attribute: Int): Boolean { 45 return context.theme.resolveAttribute(attribute, TypedValue(), true) 46 } 47 } 48