close
The Wayback Machine - https://web.archive.org/web/20150905213601/https://developer.android.com/samples/MediaBrowserService/src/com.example.android.mediabrowserservice/utils/ResourceHelper.html
Show navigation Hide navigation
MediaBrowserService / src / com.example.android.mediabrowserservice / utils /

ResourceHelper.java

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
 
17
package com.example.android.mediabrowserservice.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
    public static int getThemeColor(Context context, int attribute, int defaultColor) {
37
        int themeColor = 0;
38
        String packageName = context.getPackageName();
39
        try {
40
            Context packageContext = context.createPackageContext(packageName, 0);
41
            ApplicationInfo applicationInfo =
42
                context.getPackageManager().getApplicationInfo(packageName, 0);
43
            packageContext.setTheme(applicationInfo.theme);
44
            Resources.Theme theme = packageContext.getTheme();
45
            TypedArray ta = theme.obtainStyledAttributes(new int[] {attribute});
46
            themeColor = ta.getColor(0, defaultColor);
47
            ta.recycle();
48
        } catch (PackageManager.NameNotFoundException e) {
49
            e.printStackTrace();
50
        }
51
        return themeColor;
52
    }
53
}