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 com.example.android.supportv4.media.utils;
18 
19 import android.content.Context;
20 import android.content.pm.ApplicationInfo;
21 import android.content.pm.PackageManager;
22 import android.content.res.Resources;
23 import android.content.res.TypedArray;
24 
25 /**
26  * Generic reusable methods to handle resources.
27  */
28 public class ResourceHelper {
29     /**
30      * Get a color value from a theme attribute.
31      * @param context used for getting the color.
32      * @param attribute theme attribute.
33      * @param defaultColor default to use.
34      * @return color value
35      */
36     @SuppressWarnings({"CatchAndPrintStackTrace", "deprecation"})
getThemeColor(Context context, int attribute, int defaultColor)37     public static int getThemeColor(Context context, int attribute, int defaultColor) {
38         int themeColor = 0;
39         String packageName = context.getPackageName();
40         try {
41             Context packageContext = context.createPackageContext(packageName, 0);
42             ApplicationInfo applicationInfo =
43                 context.getPackageManager().getApplicationInfo(packageName, 0);
44             packageContext.setTheme(applicationInfo.theme);
45             Resources.Theme theme = packageContext.getTheme();
46             TypedArray ta = theme.obtainStyledAttributes(new int[] {attribute});
47             themeColor = ta.getColor(0, defaultColor);
48             ta.recycle();
49         } catch (PackageManager.NameNotFoundException e) {
50             e.printStackTrace();
51         }
52         return themeColor;
53     }
54 
ResourceHelper()55     private ResourceHelper() {
56     }
57 }
58