Resources.java revision 0810b63739c9981f993063749f804b54faed0ba5
1/*
2 * Copyright (C) 2006 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.content.res;
18
19import com.android.internal.util.XmlUtils;
20
21import org.xmlpull.v1.XmlPullParser;
22import org.xmlpull.v1.XmlPullParserException;
23
24import android.content.pm.ActivityInfo;
25import android.graphics.Movie;
26import android.graphics.drawable.Drawable;
27import android.graphics.drawable.ColorDrawable;
28import android.graphics.drawable.Drawable.ConstantState;
29import android.os.Build;
30import android.os.Bundle;
31import android.os.IBinder;
32import android.os.Trace;
33import android.util.AttributeSet;
34import android.util.DisplayMetrics;
35import android.util.Log;
36import android.util.Slog;
37import android.util.SparseArray;
38import android.util.TypedValue;
39import android.util.LongSparseArray;
40
41import java.io.IOException;
42import java.io.InputStream;
43import java.lang.ref.WeakReference;
44import java.util.Locale;
45
46import libcore.icu.NativePluralRules;
47
48/**
49 * Class for accessing an application's resources.  This sits on top of the
50 * asset manager of the application (accessible through {@link #getAssets}) and
51 * provides a high-level API for getting typed data from the assets.
52 *
53 * <p>The Android resource system keeps track of all non-code assets associated with an
54 * application. You can use this class to access your application's resources. You can generally
55 * acquire the {@link android.content.res.Resources} instance associated with your application
56 * with {@link android.content.Context#getResources getResources()}.</p>
57 *
58 * <p>The Android SDK tools compile your application's resources into the application binary
59 * at build time.  To use a resource, you must install it correctly in the source tree (inside
60 * your project's {@code res/} directory) and build your application.  As part of the build
61 * process, the SDK tools generate symbols for each resource, which you can use in your application
62 * code to access the resources.</p>
63 *
64 * <p>Using application resources makes it easy to update various characteristics of your
65 * application without modifying code, and&mdash;by providing sets of alternative
66 * resources&mdash;enables you to optimize your application for a variety of device configurations
67 * (such as for different languages and screen sizes). This is an important aspect of developing
68 * Android applications that are compatible on different types of devices.</p>
69 *
70 * <p>For more information about using resources, see the documentation about <a
71 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
72 */
73public class Resources {
74    static final String TAG = "Resources";
75
76    private static final boolean DEBUG_LOAD = false;
77    private static final boolean DEBUG_CONFIG = false;
78    private static final boolean TRACE_FOR_PRELOAD = false;
79    private static final boolean TRACE_FOR_MISS_PRELOAD = false;
80
81    private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
82            ActivityInfo.CONFIG_LAYOUT_DIRECTION);
83
84    private static final int ID_OTHER = 0x01000004;
85
86    private static final Object sSync = new Object();
87
88    // Information about preloaded resources.  Note that they are not
89    // protected by a lock, because while preloading in zygote we are all
90    // single-threaded, and after that these are immutable.
91    private static final LongSparseArray<ConstantState>[] sPreloadedDrawables;
92    private static final LongSparseArray<ConstantState> sPreloadedColorDrawables
93            = new LongSparseArray<ConstantState>();
94    private static final LongSparseArray<ColorStateList> sPreloadedColorStateLists
95            = new LongSparseArray<ColorStateList>();
96
97    // Used by BridgeResources in layoutlib
98    static Resources mSystem = null;
99
100    private static boolean sPreloaded;
101    private static int sPreloadedDensity;
102
103    // These are protected by mAccessLock.
104    private final Object mAccessLock = new Object();
105    private final Configuration mTmpConfig = new Configuration();
106    private final ThemedCaches<ConstantState> mDrawableCache =
107            new ThemedCaches<ConstantState>();
108    private final ThemedCaches<ConstantState> mColorDrawableCache =
109            new ThemedCaches<ConstantState>();
110    private final LongSparseArray<WeakReference<ColorStateList>> mColorStateListCache =
111            new LongSparseArray<WeakReference<ColorStateList>>();
112
113    private TypedValue mTmpValue = new TypedValue();
114    private boolean mPreloading;
115
116    private TypedArray mCachedStyledAttributes = null;
117
118    private int mLastCachedXmlBlockIndex = -1;
119    private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 };
120    private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4];
121
122    private final AssetManager mAssets;
123    private final Configuration mConfiguration = new Configuration();
124    private final DisplayMetrics mMetrics = new DisplayMetrics();
125    private NativePluralRules mPluralRule;
126
127    private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
128
129    @SuppressWarnings("unused")
130    private WeakReference<IBinder> mToken;
131
132    static {
133        sPreloadedDrawables = new LongSparseArray[2];
134        sPreloadedDrawables[0] = new LongSparseArray<ConstantState>();
135        sPreloadedDrawables[1] = new LongSparseArray<ConstantState>();
136    }
137
138    /**
139     * Returns the most appropriate default theme for the specified target SDK version.
140     *
141     * @param curTheme The current theme, or 0 if not specified.
142     * @param targetSdkVersion The target SDK version.
143     * @return A theme resource identifier
144     * @hide
145     */
146    public int selectDefaultTheme(int curTheme, int targetSdkVersion) {
147        return selectSystemTheme(curTheme, targetSdkVersion,
148                com.android.internal.R.array.system_theme_sdks,
149                com.android.internal.R.array.system_theme_styles);
150    }
151
152    /**
153     * Returns the most appropriate default theme for the specified target SDK version.
154     *
155     * @param curTheme The current theme, or 0 if not specified.
156     * @param targetSdkVersion The target SDK version.
157     * @param sdkArrayId Identifier for integer array resource containing
158     *        sorted minimum SDK versions. First entry must be 0.
159     * @param themeArrayId Identifier for array resource containing the
160     *        default themes that map to SDK versions.
161     * @return A theme resource identifier
162     * @hide
163     */
164    public int selectSystemTheme(
165            int curTheme, int targetSdkVersion, int sdkArrayId, int themeArrayId) {
166        if (curTheme != 0) {
167            return curTheme;
168        }
169
170        final int[] targetSdks = getIntArray(sdkArrayId);
171        final TypedArray defaultThemes = obtainTypedArray(themeArrayId);
172        for (int i = targetSdks.length - 1; i > 0; i--) {
173            if (targetSdkVersion >= targetSdks[i]) {
174                return defaultThemes.getResourceId(i, 0);
175            }
176        }
177
178        return defaultThemes.getResourceId(0, 0);
179    }
180
181    /**
182     * This exception is thrown by the resource APIs when a requested resource
183     * can not be found.
184     */
185    public static class NotFoundException extends RuntimeException {
186        public NotFoundException() {
187        }
188
189        public NotFoundException(String name) {
190            super(name);
191        }
192    }
193
194    /**
195     * Create a new Resources object on top of an existing set of assets in an
196     * AssetManager.
197     *
198     * @param assets Previously created AssetManager.
199     * @param metrics Current display metrics to consider when
200     *                selecting/computing resource values.
201     * @param config Desired device configuration to consider when
202     *               selecting/computing resource values (optional).
203     */
204    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
205        this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
206    }
207
208    /**
209     * Creates a new Resources object with CompatibilityInfo.
210     *
211     * @param assets Previously created AssetManager.
212     * @param metrics Current display metrics to consider when
213     *                selecting/computing resource values.
214     * @param config Desired device configuration to consider when
215     *               selecting/computing resource values (optional).
216     * @param compatInfo this resource's compatibility info. Must not be null.
217     * @param token The Activity token for determining stack affiliation. Usually null.
218     * @hide
219     */
220    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
221            CompatibilityInfo compatInfo, IBinder token) {
222        mAssets = assets;
223        mMetrics.setToDefaults();
224        if (compatInfo != null) {
225            mCompatibilityInfo = compatInfo;
226        }
227        mToken = new WeakReference<IBinder>(token);
228        updateConfiguration(config, metrics);
229        assets.ensureStringBlocks();
230    }
231
232    /**
233     * Return a global shared Resources object that provides access to only
234     * system resources (no application resources), and is not configured for
235     * the current screen (can not use dimension units, does not change based
236     * on orientation, etc).
237     */
238    public static Resources getSystem() {
239        synchronized (sSync) {
240            Resources ret = mSystem;
241            if (ret == null) {
242                ret = new Resources();
243                mSystem = ret;
244            }
245
246            return ret;
247        }
248    }
249
250    /**
251     * Return the string value associated with a particular resource ID.  The
252     * returned object will be a String if this is a plain string; it will be
253     * some other type of CharSequence if it is styled.
254     * {@more}
255     *
256     * @param id The desired resource identifier, as generated by the aapt
257     *           tool. This integer encodes the package, type, and resource
258     *           entry. The value 0 is an invalid identifier.
259     *
260     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
261     *
262     * @return CharSequence The string data associated with the resource, plus
263     *         possibly styled text information.
264     */
265    public CharSequence getText(int id) throws NotFoundException {
266        CharSequence res = mAssets.getResourceText(id);
267        if (res != null) {
268            return res;
269        }
270        throw new NotFoundException("String resource ID #0x"
271                                    + Integer.toHexString(id));
272    }
273
274    /**
275     * Returns the character sequence necessary for grammatically correct pluralization
276     * of the given resource ID for the given quantity.
277     * Note that the character sequence is selected based solely on grammatical necessity,
278     * and that such rules differ between languages. Do not assume you know which string
279     * will be returned for a given quantity. See
280     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
281     * for more detail.
282     *
283     * @param id The desired resource identifier, as generated by the aapt
284     *           tool. This integer encodes the package, type, and resource
285     *           entry. The value 0 is an invalid identifier.
286     * @param quantity The number used to get the correct string for the current language's
287     *           plural rules.
288     *
289     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
290     *
291     * @return CharSequence The string data associated with the resource, plus
292     *         possibly styled text information.
293     */
294    public CharSequence getQuantityText(int id, int quantity) throws NotFoundException {
295        NativePluralRules rule = getPluralRule();
296        CharSequence res = mAssets.getResourceBagText(id,
297                attrForQuantityCode(rule.quantityForInt(quantity)));
298        if (res != null) {
299            return res;
300        }
301        res = mAssets.getResourceBagText(id, ID_OTHER);
302        if (res != null) {
303            return res;
304        }
305        throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
306                + " quantity=" + quantity
307                + " item=" + stringForQuantityCode(rule.quantityForInt(quantity)));
308    }
309
310    private NativePluralRules getPluralRule() {
311        synchronized (sSync) {
312            if (mPluralRule == null) {
313                mPluralRule = NativePluralRules.forLocale(mConfiguration.locale);
314            }
315            return mPluralRule;
316        }
317    }
318
319    private static int attrForQuantityCode(int quantityCode) {
320        switch (quantityCode) {
321            case NativePluralRules.ZERO: return 0x01000005;
322            case NativePluralRules.ONE:  return 0x01000006;
323            case NativePluralRules.TWO:  return 0x01000007;
324            case NativePluralRules.FEW:  return 0x01000008;
325            case NativePluralRules.MANY: return 0x01000009;
326            default:                     return ID_OTHER;
327        }
328    }
329
330    private static String stringForQuantityCode(int quantityCode) {
331        switch (quantityCode) {
332            case NativePluralRules.ZERO: return "zero";
333            case NativePluralRules.ONE:  return "one";
334            case NativePluralRules.TWO:  return "two";
335            case NativePluralRules.FEW:  return "few";
336            case NativePluralRules.MANY: return "many";
337            default:                     return "other";
338        }
339    }
340
341    /**
342     * Return the string value associated with a particular resource ID.  It
343     * will be stripped of any styled text information.
344     * {@more}
345     *
346     * @param id The desired resource identifier, as generated by the aapt
347     *           tool. This integer encodes the package, type, and resource
348     *           entry. The value 0 is an invalid identifier.
349     *
350     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
351     *
352     * @return String The string data associated with the resource,
353     * stripped of styled text information.
354     */
355    public String getString(int id) throws NotFoundException {
356        CharSequence res = getText(id);
357        if (res != null) {
358            return res.toString();
359        }
360        throw new NotFoundException("String resource ID #0x"
361                                    + Integer.toHexString(id));
362    }
363
364
365    /**
366     * Return the string value associated with a particular resource ID,
367     * substituting the format arguments as defined in {@link java.util.Formatter}
368     * and {@link java.lang.String#format}. It will be stripped of any styled text
369     * information.
370     * {@more}
371     *
372     * @param id The desired resource identifier, as generated by the aapt
373     *           tool. This integer encodes the package, type, and resource
374     *           entry. The value 0 is an invalid identifier.
375     *
376     * @param formatArgs The format arguments that will be used for substitution.
377     *
378     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
379     *
380     * @return String The string data associated with the resource,
381     * stripped of styled text information.
382     */
383    public String getString(int id, Object... formatArgs) throws NotFoundException {
384        String raw = getString(id);
385        return String.format(mConfiguration.locale, raw, formatArgs);
386    }
387
388    /**
389     * Formats the string necessary for grammatically correct pluralization
390     * of the given resource ID for the given quantity, using the given arguments.
391     * Note that the string is selected based solely on grammatical necessity,
392     * and that such rules differ between languages. Do not assume you know which string
393     * will be returned for a given quantity. See
394     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
395     * for more detail.
396     *
397     * <p>Substitution of format arguments works as if using
398     * {@link java.util.Formatter} and {@link java.lang.String#format}.
399     * The resulting string will be stripped of any styled text information.
400     *
401     * @param id The desired resource identifier, as generated by the aapt
402     *           tool. This integer encodes the package, type, and resource
403     *           entry. The value 0 is an invalid identifier.
404     * @param quantity The number used to get the correct string for the current language's
405     *           plural rules.
406     * @param formatArgs The format arguments that will be used for substitution.
407     *
408     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
409     *
410     * @return String The string data associated with the resource,
411     * stripped of styled text information.
412     */
413    public String getQuantityString(int id, int quantity, Object... formatArgs)
414            throws NotFoundException {
415        String raw = getQuantityText(id, quantity).toString();
416        return String.format(mConfiguration.locale, raw, formatArgs);
417    }
418
419    /**
420     * Returns the string necessary for grammatically correct pluralization
421     * of the given resource ID for the given quantity.
422     * Note that the string is selected based solely on grammatical necessity,
423     * and that such rules differ between languages. Do not assume you know which string
424     * will be returned for a given quantity. See
425     * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
426     * for more detail.
427     *
428     * @param id The desired resource identifier, as generated by the aapt
429     *           tool. This integer encodes the package, type, and resource
430     *           entry. The value 0 is an invalid identifier.
431     * @param quantity The number used to get the correct string for the current language's
432     *           plural rules.
433     *
434     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
435     *
436     * @return String The string data associated with the resource,
437     * stripped of styled text information.
438     */
439    public String getQuantityString(int id, int quantity) throws NotFoundException {
440        return getQuantityText(id, quantity).toString();
441    }
442
443    /**
444     * Return the string value associated with a particular resource ID.  The
445     * returned object will be a String if this is a plain string; it will be
446     * some other type of CharSequence if it is styled.
447     *
448     * @param id The desired resource identifier, as generated by the aapt
449     *           tool. This integer encodes the package, type, and resource
450     *           entry. The value 0 is an invalid identifier.
451     *
452     * @param def The default CharSequence to return.
453     *
454     * @return CharSequence The string data associated with the resource, plus
455     *         possibly styled text information, or def if id is 0 or not found.
456     */
457    public CharSequence getText(int id, CharSequence def) {
458        CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
459        return res != null ? res : def;
460    }
461
462    /**
463     * Return the styled text array associated with a particular resource ID.
464     *
465     * @param id The desired resource identifier, as generated by the aapt
466     *           tool. This integer encodes the package, type, and resource
467     *           entry. The value 0 is an invalid identifier.
468     *
469     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
470     *
471     * @return The styled text array associated with the resource.
472     */
473    public CharSequence[] getTextArray(int id) throws NotFoundException {
474        CharSequence[] res = mAssets.getResourceTextArray(id);
475        if (res != null) {
476            return res;
477        }
478        throw new NotFoundException("Text array resource ID #0x"
479                                    + Integer.toHexString(id));
480    }
481
482    /**
483     * Return the string array associated with a particular resource ID.
484     *
485     * @param id The desired resource identifier, as generated by the aapt
486     *           tool. This integer encodes the package, type, and resource
487     *           entry. The value 0 is an invalid identifier.
488     *
489     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
490     *
491     * @return The string array associated with the resource.
492     */
493    public String[] getStringArray(int id) throws NotFoundException {
494        String[] res = mAssets.getResourceStringArray(id);
495        if (res != null) {
496            return res;
497        }
498        throw new NotFoundException("String array resource ID #0x"
499                                    + Integer.toHexString(id));
500    }
501
502    /**
503     * Return the int array associated with a particular resource ID.
504     *
505     * @param id The desired resource identifier, as generated by the aapt
506     *           tool. This integer encodes the package, type, and resource
507     *           entry. The value 0 is an invalid identifier.
508     *
509     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
510     *
511     * @return The int array associated with the resource.
512     */
513    public int[] getIntArray(int id) throws NotFoundException {
514        int[] res = mAssets.getArrayIntResource(id);
515        if (res != null) {
516            return res;
517        }
518        throw new NotFoundException("Int array resource ID #0x"
519                                    + Integer.toHexString(id));
520    }
521
522    /**
523     * Return an array of heterogeneous values.
524     *
525     * @param id The desired resource identifier, as generated by the aapt
526     *           tool. This integer encodes the package, type, and resource
527     *           entry. The value 0 is an invalid identifier.
528     *
529     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
530     *
531     * @return Returns a TypedArray holding an array of the array values.
532     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
533     * when done with it.
534     */
535    public TypedArray obtainTypedArray(int id) throws NotFoundException {
536        int len = mAssets.getArraySize(id);
537        if (len < 0) {
538            throw new NotFoundException("Array resource ID #0x"
539                                        + Integer.toHexString(id));
540        }
541
542        TypedArray array = TypedArray.obtain(this, len);
543        array.mLength = mAssets.retrieveArray(id, array.mData);
544        array.mIndices[0] = 0;
545
546        return array;
547    }
548
549    /**
550     * Retrieve a dimensional for a particular resource ID.  Unit
551     * conversions are based on the current {@link DisplayMetrics} associated
552     * with the resources.
553     *
554     * @param id The desired resource identifier, as generated by the aapt
555     *           tool. This integer encodes the package, type, and resource
556     *           entry. The value 0 is an invalid identifier.
557     *
558     * @return Resource dimension value multiplied by the appropriate
559     * metric.
560     *
561     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
562     *
563     * @see #getDimensionPixelOffset
564     * @see #getDimensionPixelSize
565     */
566    public float getDimension(int id) throws NotFoundException {
567        synchronized (mAccessLock) {
568            TypedValue value = mTmpValue;
569            if (value == null) {
570                mTmpValue = value = new TypedValue();
571            }
572            getValue(id, value, true);
573            if (value.type == TypedValue.TYPE_DIMENSION) {
574                return TypedValue.complexToDimension(value.data, mMetrics);
575            }
576            throw new NotFoundException(
577                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
578                    + Integer.toHexString(value.type) + " is not valid");
579        }
580    }
581
582    /**
583     * Retrieve a dimensional for a particular resource ID for use
584     * as an offset in raw pixels.  This is the same as
585     * {@link #getDimension}, except the returned value is converted to
586     * integer pixels for you.  An offset conversion involves simply
587     * truncating the base value to an integer.
588     *
589     * @param id The desired resource identifier, as generated by the aapt
590     *           tool. This integer encodes the package, type, and resource
591     *           entry. The value 0 is an invalid identifier.
592     *
593     * @return Resource dimension value multiplied by the appropriate
594     * metric and truncated to integer pixels.
595     *
596     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
597     *
598     * @see #getDimension
599     * @see #getDimensionPixelSize
600     */
601    public int getDimensionPixelOffset(int id) throws NotFoundException {
602        synchronized (mAccessLock) {
603            TypedValue value = mTmpValue;
604            if (value == null) {
605                mTmpValue = value = new TypedValue();
606            }
607            getValue(id, value, true);
608            if (value.type == TypedValue.TYPE_DIMENSION) {
609                return TypedValue.complexToDimensionPixelOffset(
610                        value.data, mMetrics);
611            }
612            throw new NotFoundException(
613                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
614                    + Integer.toHexString(value.type) + " is not valid");
615        }
616    }
617
618    /**
619     * Retrieve a dimensional for a particular resource ID for use
620     * as a size in raw pixels.  This is the same as
621     * {@link #getDimension}, except the returned value is converted to
622     * integer pixels for use as a size.  A size conversion involves
623     * rounding the base value, and ensuring that a non-zero base value
624     * is at least one pixel in size.
625     *
626     * @param id The desired resource identifier, as generated by the aapt
627     *           tool. This integer encodes the package, type, and resource
628     *           entry. The value 0 is an invalid identifier.
629     *
630     * @return Resource dimension value multiplied by the appropriate
631     * metric and truncated to integer pixels.
632     *
633     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
634     *
635     * @see #getDimension
636     * @see #getDimensionPixelOffset
637     */
638    public int getDimensionPixelSize(int id) throws NotFoundException {
639        synchronized (mAccessLock) {
640            TypedValue value = mTmpValue;
641            if (value == null) {
642                mTmpValue = value = new TypedValue();
643            }
644            getValue(id, value, true);
645            if (value.type == TypedValue.TYPE_DIMENSION) {
646                return TypedValue.complexToDimensionPixelSize(
647                        value.data, mMetrics);
648            }
649            throw new NotFoundException(
650                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
651                    + Integer.toHexString(value.type) + " is not valid");
652        }
653    }
654
655    /**
656     * Retrieve a fractional unit for a particular resource ID.
657     *
658     * @param id The desired resource identifier, as generated by the aapt
659     *           tool. This integer encodes the package, type, and resource
660     *           entry. The value 0 is an invalid identifier.
661     * @param base The base value of this fraction.  In other words, a
662     *             standard fraction is multiplied by this value.
663     * @param pbase The parent base value of this fraction.  In other
664     *             words, a parent fraction (nn%p) is multiplied by this
665     *             value.
666     *
667     * @return Attribute fractional value multiplied by the appropriate
668     * base value.
669     *
670     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
671     */
672    public float getFraction(int id, int base, int pbase) {
673        synchronized (mAccessLock) {
674            TypedValue value = mTmpValue;
675            if (value == null) {
676                mTmpValue = value = new TypedValue();
677            }
678            getValue(id, value, true);
679            if (value.type == TypedValue.TYPE_FRACTION) {
680                return TypedValue.complexToFraction(value.data, base, pbase);
681            }
682            throw new NotFoundException(
683                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
684                    + Integer.toHexString(value.type) + " is not valid");
685        }
686    }
687
688    /**
689     * Return a drawable object associated with a particular resource ID.
690     * Various types of objects will be returned depending on the underlying
691     * resource -- for example, a solid color, PNG image, scalable image, etc.
692     * The Drawable API hides these implementation details.
693     *
694     * <p class="note"><strong>Note:</strong> Prior to
695     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
696     * would not correctly retrieve the final configuration density when
697     * the resource ID passed here is an alias to another Drawable resource.
698     * This means that if the density configuration of the alias resource
699     * is different than the actual resource, the density of the returned
700     * Drawable would be incorrect, resulting in bad scaling.  To work
701     * around this, you can instead retrieve the Drawable through
702     * {@link TypedArray#getDrawable TypedArray.getDrawable}.  Use
703     * {@link android.content.Context#obtainStyledAttributes(int[])
704     * Context.obtainStyledAttributes} with
705     * an array containing the resource ID of interest to create the TypedArray.</p>
706     *
707     * @param id The desired resource identifier, as generated by the aapt
708     *           tool. This integer encodes the package, type, and resource
709     *           entry. The value 0 is an invalid identifier.
710     * @return Drawable An object that can be used to draw this resource.
711     * @throws NotFoundException Throws NotFoundException if the given ID does
712     *         not exist.
713     */
714    public Drawable getDrawable(int id) throws NotFoundException {
715        return getDrawable(id, null);
716    }
717
718    /**
719     * Return a drawable object associated with a particular resource ID and
720     * styled for the specified theme.
721     *
722     * @param id The desired resource identifier, as generated by the aapt
723     *           tool. This integer encodes the package, type, and resource
724     *           entry. The value 0 is an invalid identifier.
725     * @param theme The theme used to style the drawable attributes.
726     * @return Drawable An object that can be used to draw this resource.
727     * @throws NotFoundException Throws NotFoundException if the given ID does
728     *         not exist.
729     */
730    public Drawable getDrawable(int id, Theme theme) throws NotFoundException {
731        TypedValue value;
732        synchronized (mAccessLock) {
733            value = mTmpValue;
734            if (value == null) {
735                value = new TypedValue();
736            } else {
737                mTmpValue = null;
738            }
739            getValue(id, value, true);
740        }
741        final Drawable res = loadDrawable(value, id, theme);
742        synchronized (mAccessLock) {
743            if (mTmpValue == null) {
744                mTmpValue = value;
745            }
746        }
747        return res;
748    }
749
750    /**
751     * Return a drawable object associated with a particular resource ID for the
752     * given screen density in DPI. This will set the drawable's density to be
753     * the device's density multiplied by the ratio of actual drawable density
754     * to requested density. This allows the drawable to be scaled up to the
755     * correct size if needed. Various types of objects will be returned
756     * depending on the underlying resource -- for example, a solid color, PNG
757     * image, scalable image, etc. The Drawable API hides these implementation
758     * details.
759     *
760     * @param id The desired resource identifier, as generated by the aapt tool.
761     *            This integer encodes the package, type, and resource entry.
762     *            The value 0 is an invalid identifier.
763     * @param density the desired screen density indicated by the resource as
764     *            found in {@link DisplayMetrics}.
765     * @return Drawable An object that can be used to draw this resource.
766     * @throws NotFoundException Throws NotFoundException if the given ID does
767     *             not exist.
768     * @see #getDrawableForDensity(int, int, Theme)
769     */
770    public Drawable getDrawableForDensity(int id, int density) throws NotFoundException {
771        return getDrawableForDensity(id, density, null);
772    }
773
774    /**
775     * Return a drawable object associated with a particular resource ID for the
776     * given screen density in DPI and styled for the specified theme.
777     *
778     * @param id The desired resource identifier, as generated by the aapt tool.
779     *            This integer encodes the package, type, and resource entry.
780     *            The value 0 is an invalid identifier.
781     * @param density The desired screen density indicated by the resource as
782     *            found in {@link DisplayMetrics}.
783     * @param theme The theme used to style the drawable attributes.
784     * @return Drawable An object that can be used to draw this resource.
785     * @throws NotFoundException Throws NotFoundException if the given ID does
786     *             not exist.
787     */
788    public Drawable getDrawableForDensity(int id, int density, Theme theme) {
789        TypedValue value;
790        synchronized (mAccessLock) {
791            value = mTmpValue;
792            if (value == null) {
793                value = new TypedValue();
794            } else {
795                mTmpValue = null;
796            }
797            getValueForDensity(id, density, value, true);
798
799            /*
800             * Pretend the requested density is actually the display density. If
801             * the drawable returned is not the requested density, then force it
802             * to be scaled later by dividing its density by the ratio of
803             * requested density to actual device density. Drawables that have
804             * undefined density or no density don't need to be handled here.
805             */
806            if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
807                if (value.density == density) {
808                    value.density = mMetrics.densityDpi;
809                } else {
810                    value.density = (value.density * mMetrics.densityDpi) / density;
811                }
812            }
813        }
814
815        final Drawable res = loadDrawable(value, id, theme);
816        synchronized (mAccessLock) {
817            if (mTmpValue == null) {
818                mTmpValue = value;
819            }
820        }
821        return res;
822    }
823
824    /**
825     * Return a movie object associated with the particular resource ID.
826     * @param id The desired resource identifier, as generated by the aapt
827     *           tool. This integer encodes the package, type, and resource
828     *           entry. The value 0 is an invalid identifier.
829     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
830     *
831     */
832    public Movie getMovie(int id) throws NotFoundException {
833        InputStream is = openRawResource(id);
834        Movie movie = Movie.decodeStream(is);
835        try {
836            is.close();
837        }
838        catch (java.io.IOException e) {
839            // don't care, since the return value is valid
840        }
841        return movie;
842    }
843
844    /**
845     * Return a color integer associated with a particular resource ID.
846     * If the resource holds a complex
847     * {@link android.content.res.ColorStateList}, then the default color from
848     * the set is returned.
849     *
850     * @param id The desired resource identifier, as generated by the aapt
851     *           tool. This integer encodes the package, type, and resource
852     *           entry. The value 0 is an invalid identifier.
853     *
854     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
855     *
856     * @return Returns a single color value in the form 0xAARRGGBB.
857     */
858    public int getColor(int id) throws NotFoundException {
859        TypedValue value;
860        synchronized (mAccessLock) {
861            value = mTmpValue;
862            if (value == null) {
863                value = new TypedValue();
864            }
865            getValue(id, value, true);
866            if (value.type >= TypedValue.TYPE_FIRST_INT
867                && value.type <= TypedValue.TYPE_LAST_INT) {
868                mTmpValue = value;
869                return value.data;
870            } else if (value.type != TypedValue.TYPE_STRING) {
871                throw new NotFoundException(
872                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
873                    + Integer.toHexString(value.type) + " is not valid");
874            }
875            mTmpValue = null;
876        }
877        ColorStateList csl = loadColorStateList(value, id);
878        synchronized (mAccessLock) {
879            if (mTmpValue == null) {
880                mTmpValue = value;
881            }
882        }
883        return csl.getDefaultColor();
884    }
885
886    /**
887     * Return a color state list associated with a particular resource ID.  The
888     * resource may contain either a single raw color value, or a complex
889     * {@link android.content.res.ColorStateList} holding multiple possible colors.
890     *
891     * @param id The desired resource identifier of a {@link ColorStateList},
892     *        as generated by the aapt tool. This integer encodes the package, type, and resource
893     *        entry. The value 0 is an invalid identifier.
894     *
895     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
896     *
897     * @return Returns a ColorStateList object containing either a single
898     * solid color or multiple colors that can be selected based on a state.
899     */
900    public ColorStateList getColorStateList(int id) throws NotFoundException {
901        TypedValue value;
902        synchronized (mAccessLock) {
903            value = mTmpValue;
904            if (value == null) {
905                value = new TypedValue();
906            } else {
907                mTmpValue = null;
908            }
909            getValue(id, value, true);
910        }
911        ColorStateList res = loadColorStateList(value, id);
912        synchronized (mAccessLock) {
913            if (mTmpValue == null) {
914                mTmpValue = value;
915            }
916        }
917        return res;
918    }
919
920    /**
921     * Return a boolean associated with a particular resource ID.  This can be
922     * used with any integral resource value, and will return true if it is
923     * non-zero.
924     *
925     * @param id The desired resource identifier, as generated by the aapt
926     *           tool. This integer encodes the package, type, and resource
927     *           entry. The value 0 is an invalid identifier.
928     *
929     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
930     *
931     * @return Returns the boolean value contained in the resource.
932     */
933    public boolean getBoolean(int id) throws NotFoundException {
934        synchronized (mAccessLock) {
935            TypedValue value = mTmpValue;
936            if (value == null) {
937                mTmpValue = value = new TypedValue();
938            }
939            getValue(id, value, true);
940            if (value.type >= TypedValue.TYPE_FIRST_INT
941                && value.type <= TypedValue.TYPE_LAST_INT) {
942                return value.data != 0;
943            }
944            throw new NotFoundException(
945                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
946                + Integer.toHexString(value.type) + " is not valid");
947        }
948    }
949
950    /**
951     * Return an integer associated with a particular resource ID.
952     *
953     * @param id The desired resource identifier, as generated by the aapt
954     *           tool. This integer encodes the package, type, and resource
955     *           entry. The value 0 is an invalid identifier.
956     *
957     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
958     *
959     * @return Returns the integer value contained in the resource.
960     */
961    public int getInteger(int id) throws NotFoundException {
962        synchronized (mAccessLock) {
963            TypedValue value = mTmpValue;
964            if (value == null) {
965                mTmpValue = value = new TypedValue();
966            }
967            getValue(id, value, true);
968            if (value.type >= TypedValue.TYPE_FIRST_INT
969                && value.type <= TypedValue.TYPE_LAST_INT) {
970                return value.data;
971            }
972            throw new NotFoundException(
973                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
974                + Integer.toHexString(value.type) + " is not valid");
975        }
976    }
977
978    /**
979     * Return an XmlResourceParser through which you can read a view layout
980     * description for the given resource ID.  This parser has limited
981     * functionality -- in particular, you can't change its input, and only
982     * the high-level events are available.
983     *
984     * <p>This function is really a simple wrapper for calling
985     * {@link #getXml} with a layout resource.
986     *
987     * @param id The desired resource identifier, as generated by the aapt
988     *           tool. This integer encodes the package, type, and resource
989     *           entry. The value 0 is an invalid identifier.
990     *
991     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
992     *
993     * @return A new parser object through which you can read
994     *         the XML data.
995     *
996     * @see #getXml
997     */
998    public XmlResourceParser getLayout(int id) throws NotFoundException {
999        return loadXmlResourceParser(id, "layout");
1000    }
1001
1002    /**
1003     * Return an XmlResourceParser through which you can read an animation
1004     * description for the given resource ID.  This parser has limited
1005     * functionality -- in particular, you can't change its input, and only
1006     * the high-level events are available.
1007     *
1008     * <p>This function is really a simple wrapper for calling
1009     * {@link #getXml} with an animation resource.
1010     *
1011     * @param id The desired resource identifier, as generated by the aapt
1012     *           tool. This integer encodes the package, type, and resource
1013     *           entry. The value 0 is an invalid identifier.
1014     *
1015     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1016     *
1017     * @return A new parser object through which you can read
1018     *         the XML data.
1019     *
1020     * @see #getXml
1021     */
1022    public XmlResourceParser getAnimation(int id) throws NotFoundException {
1023        return loadXmlResourceParser(id, "anim");
1024    }
1025
1026    /**
1027     * Return an XmlResourceParser through which you can read a generic XML
1028     * resource for the given resource ID.
1029     *
1030     * <p>The XmlPullParser implementation returned here has some limited
1031     * functionality.  In particular, you can't change its input, and only
1032     * high-level parsing events are available (since the document was
1033     * pre-parsed for you at build time, which involved merging text and
1034     * stripping comments).
1035     *
1036     * @param id The desired resource identifier, as generated by the aapt
1037     *           tool. This integer encodes the package, type, and resource
1038     *           entry. The value 0 is an invalid identifier.
1039     *
1040     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1041     *
1042     * @return A new parser object through which you can read
1043     *         the XML data.
1044     *
1045     * @see android.util.AttributeSet
1046     */
1047    public XmlResourceParser getXml(int id) throws NotFoundException {
1048        return loadXmlResourceParser(id, "xml");
1049    }
1050
1051    /**
1052     * Open a data stream for reading a raw resource.  This can only be used
1053     * with resources whose value is the name of an asset files -- that is, it can be
1054     * used to open drawable, sound, and raw resources; it will fail on string
1055     * and color resources.
1056     *
1057     * @param id The resource identifier to open, as generated by the appt
1058     *           tool.
1059     *
1060     * @return InputStream Access to the resource data.
1061     *
1062     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1063     *
1064     */
1065    public InputStream openRawResource(int id) throws NotFoundException {
1066        TypedValue value;
1067        synchronized (mAccessLock) {
1068            value = mTmpValue;
1069            if (value == null) {
1070                value = new TypedValue();
1071            } else {
1072                mTmpValue = null;
1073            }
1074        }
1075        InputStream res = openRawResource(id, value);
1076        synchronized (mAccessLock) {
1077            if (mTmpValue == null) {
1078                mTmpValue = value;
1079            }
1080        }
1081        return res;
1082    }
1083
1084    /**
1085     * Open a data stream for reading a raw resource.  This can only be used
1086     * with resources whose value is the name of an asset file -- that is, it can be
1087     * used to open drawable, sound, and raw resources; it will fail on string
1088     * and color resources.
1089     *
1090     * @param id The resource identifier to open, as generated by the appt tool.
1091     * @param value The TypedValue object to hold the resource information.
1092     *
1093     * @return InputStream Access to the resource data.
1094     *
1095     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1096     */
1097    public InputStream openRawResource(int id, TypedValue value) throws NotFoundException {
1098        getValue(id, value, true);
1099
1100        try {
1101            return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1102                    AssetManager.ACCESS_STREAMING);
1103        } catch (Exception e) {
1104            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1105                    " from drawable resource ID #0x" + Integer.toHexString(id));
1106            rnf.initCause(e);
1107            throw rnf;
1108        }
1109    }
1110
1111    /**
1112     * Open a file descriptor for reading a raw resource.  This can only be used
1113     * with resources whose value is the name of an asset files -- that is, it can be
1114     * used to open drawable, sound, and raw resources; it will fail on string
1115     * and color resources.
1116     *
1117     * <p>This function only works for resources that are stored in the package
1118     * as uncompressed data, which typically includes things like mp3 files
1119     * and png images.
1120     *
1121     * @param id The resource identifier to open, as generated by the appt
1122     *           tool.
1123     *
1124     * @return AssetFileDescriptor A new file descriptor you can use to read
1125     * the resource.  This includes the file descriptor itself, as well as the
1126     * offset and length of data where the resource appears in the file.  A
1127     * null is returned if the file exists but is compressed.
1128     *
1129     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1130     *
1131     */
1132    public AssetFileDescriptor openRawResourceFd(int id) throws NotFoundException {
1133        TypedValue value;
1134        synchronized (mAccessLock) {
1135            value = mTmpValue;
1136            if (value == null) {
1137                value = new TypedValue();
1138            } else {
1139                mTmpValue = null;
1140            }
1141            getValue(id, value, true);
1142        }
1143        try {
1144            return mAssets.openNonAssetFd(
1145                value.assetCookie, value.string.toString());
1146        } catch (Exception e) {
1147            NotFoundException rnf = new NotFoundException(
1148                "File " + value.string.toString()
1149                + " from drawable resource ID #0x"
1150                + Integer.toHexString(id));
1151            rnf.initCause(e);
1152            throw rnf;
1153        } finally {
1154            synchronized (mAccessLock) {
1155                if (mTmpValue == null) {
1156                    mTmpValue = value;
1157                }
1158            }
1159        }
1160    }
1161
1162    /**
1163     * Return the raw data associated with a particular resource ID.
1164     *
1165     * @param id The desired resource identifier, as generated by the aapt
1166     *           tool. This integer encodes the package, type, and resource
1167     *           entry. The value 0 is an invalid identifier.
1168     * @param outValue Object in which to place the resource data.
1169     * @param resolveRefs If true, a resource that is a reference to another
1170     *                    resource will be followed so that you receive the
1171     *                    actual final resource data.  If false, the TypedValue
1172     *                    will be filled in with the reference itself.
1173     *
1174     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1175     *
1176     */
1177    public void getValue(int id, TypedValue outValue, boolean resolveRefs)
1178            throws NotFoundException {
1179        boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
1180        if (found) {
1181            return;
1182        }
1183        throw new NotFoundException("Resource ID #0x"
1184                                    + Integer.toHexString(id));
1185    }
1186
1187    /**
1188     * Get the raw value associated with a resource with associated density.
1189     *
1190     * @param id resource identifier
1191     * @param density density in DPI
1192     * @param resolveRefs If true, a resource that is a reference to another
1193     *            resource will be followed so that you receive the actual final
1194     *            resource data. If false, the TypedValue will be filled in with
1195     *            the reference itself.
1196     * @throws NotFoundException Throws NotFoundException if the given ID does
1197     *             not exist.
1198     * @see #getValue(String, TypedValue, boolean)
1199     */
1200    public void getValueForDensity(int id, int density, TypedValue outValue, boolean resolveRefs)
1201            throws NotFoundException {
1202        boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1203        if (found) {
1204            return;
1205        }
1206        throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1207    }
1208
1209    /**
1210     * Return the raw data associated with a particular resource ID.
1211     * See getIdentifier() for information on how names are mapped to resource
1212     * IDs, and getString(int) for information on how string resources are
1213     * retrieved.
1214     *
1215     * <p>Note: use of this function is discouraged.  It is much more
1216     * efficient to retrieve resources by identifier than by name.
1217     *
1218     * @param name The name of the desired resource.  This is passed to
1219     *             getIdentifier() with a default type of "string".
1220     * @param outValue Object in which to place the resource data.
1221     * @param resolveRefs If true, a resource that is a reference to another
1222     *                    resource will be followed so that you receive the
1223     *                    actual final resource data.  If false, the TypedValue
1224     *                    will be filled in with the reference itself.
1225     *
1226     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1227     *
1228     */
1229    public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1230            throws NotFoundException {
1231        int id = getIdentifier(name, "string", null);
1232        if (id != 0) {
1233            getValue(id, outValue, resolveRefs);
1234            return;
1235        }
1236        throw new NotFoundException("String resource name " + name);
1237    }
1238
1239    /**
1240     * This class holds the current attribute values for a particular theme.
1241     * In other words, a Theme is a set of values for resource attributes;
1242     * these are used in conjunction with {@link TypedArray}
1243     * to resolve the final value for an attribute.
1244     *
1245     * <p>The Theme's attributes come into play in two ways: (1) a styled
1246     * attribute can explicit reference a value in the theme through the
1247     * "?themeAttribute" syntax; (2) if no value has been defined for a
1248     * particular styled attribute, as a last resort we will try to find that
1249     * attribute's value in the Theme.
1250     *
1251     * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1252     * retrieve XML attributes with style and theme information applied.
1253     */
1254    public final class Theme {
1255        /**
1256         * Place new attribute values into the theme.  The style resource
1257         * specified by <var>resid</var> will be retrieved from this Theme's
1258         * resources, its values placed into the Theme object.
1259         *
1260         * <p>The semantics of this function depends on the <var>force</var>
1261         * argument:  If false, only values that are not already defined in
1262         * the theme will be copied from the system resource; otherwise, if
1263         * any of the style's attributes are already defined in the theme, the
1264         * current values in the theme will be overwritten.
1265         *
1266         * @param resid The resource ID of a style resource from which to
1267         *              obtain attribute values.
1268         * @param force If true, values in the style resource will always be
1269         *              used in the theme; otherwise, they will only be used
1270         *              if not already defined in the theme.
1271         */
1272        public void applyStyle(int resid, boolean force) {
1273            AssetManager.applyThemeStyle(mTheme, resid, force);
1274
1275            // TODO: In very rare cases, we may end up with a hybrid theme
1276            // that can't map to a single theme ID.
1277            mThemeResId = resid;
1278        }
1279
1280        /**
1281         * Set this theme to hold the same contents as the theme
1282         * <var>other</var>.  If both of these themes are from the same
1283         * Resources object, they will be identical after this function
1284         * returns.  If they are from different Resources, only the resources
1285         * they have in common will be set in this theme.
1286         *
1287         * @param other The existing Theme to copy from.
1288         */
1289        public void setTo(Theme other) {
1290            AssetManager.copyTheme(mTheme, other.mTheme);
1291
1292            mThemeResId = other.mThemeResId;
1293        }
1294
1295        /**
1296         * Return a TypedArray holding the values defined by
1297         * <var>Theme</var> which are listed in <var>attrs</var>.
1298         *
1299         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1300         * with the array.
1301         *
1302         * @param attrs The desired attributes.
1303         *
1304         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1305         *
1306         * @return Returns a TypedArray holding an array of the attribute values.
1307         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1308         * when done with it.
1309         *
1310         * @see Resources#obtainAttributes
1311         * @see #obtainStyledAttributes(int, int[])
1312         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1313         */
1314        public TypedArray obtainStyledAttributes(int[] attrs) {
1315            final int len = attrs.length;
1316            final TypedArray array = TypedArray.obtain(Resources.this, len);
1317            array.mTheme = this;
1318            AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
1319            return array;
1320        }
1321
1322        /**
1323         * Return a TypedArray holding the values defined by the style
1324         * resource <var>resid</var> which are listed in <var>attrs</var>.
1325         *
1326         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1327         * with the array.
1328         *
1329         * @param resid The desired style resource.
1330         * @param attrs The desired attributes in the style.
1331         *
1332         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1333         *
1334         * @return Returns a TypedArray holding an array of the attribute values.
1335         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1336         * when done with it.
1337         *
1338         * @see Resources#obtainAttributes
1339         * @see #obtainStyledAttributes(int[])
1340         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1341         */
1342        public TypedArray obtainStyledAttributes(int resid, int[] attrs) throws NotFoundException {
1343            final int len = attrs.length;
1344            final TypedArray array = TypedArray.obtain(Resources.this, len);
1345            array.mTheme = this;
1346            if (false) {
1347                int[] data = array.mData;
1348
1349                System.out.println("**********************************************************");
1350                System.out.println("**********************************************************");
1351                System.out.println("**********************************************************");
1352                System.out.println("Attributes:");
1353                String s = "  Attrs:";
1354                int i;
1355                for (i=0; i<attrs.length; i++) {
1356                    s = s + " 0x" + Integer.toHexString(attrs[i]);
1357                }
1358                System.out.println(s);
1359                s = "  Found:";
1360                TypedValue value = new TypedValue();
1361                for (i=0; i<attrs.length; i++) {
1362                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
1363                    value.type = data[d+AssetManager.STYLE_TYPE];
1364                    value.data = data[d+AssetManager.STYLE_DATA];
1365                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1366                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1367                    s = s + " 0x" + Integer.toHexString(attrs[i])
1368                        + "=" + value;
1369                }
1370                System.out.println(s);
1371            }
1372            AssetManager.applyStyle(mTheme, 0, resid, 0, attrs, array.mData, array.mIndices);
1373            return array;
1374        }
1375
1376        /**
1377         * Return a TypedArray holding the attribute values in
1378         * <var>set</var>
1379         * that are listed in <var>attrs</var>.  In addition, if the given
1380         * AttributeSet specifies a style class (through the "style" attribute),
1381         * that style will be applied on top of the base attributes it defines.
1382         *
1383         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1384         * with the array.
1385         *
1386         * <p>When determining the final value of a particular attribute, there
1387         * are four inputs that come into play:</p>
1388         *
1389         * <ol>
1390         *     <li> Any attribute values in the given AttributeSet.
1391         *     <li> The style resource specified in the AttributeSet (named
1392         *     "style").
1393         *     <li> The default style specified by <var>defStyleAttr</var> and
1394         *     <var>defStyleRes</var>
1395         *     <li> The base values in this theme.
1396         * </ol>
1397         *
1398         * <p>Each of these inputs is considered in-order, with the first listed
1399         * taking precedence over the following ones.  In other words, if in the
1400         * AttributeSet you have supplied <code>&lt;Button
1401         * textColor="#ff000000"&gt;</code>, then the button's text will
1402         * <em>always</em> be black, regardless of what is specified in any of
1403         * the styles.
1404         *
1405         * @param set The base set of attribute values.  May be null.
1406         * @param attrs The desired attributes to be retrieved.
1407         * @param defStyleAttr An attribute in the current theme that contains a
1408         *                     reference to a style resource that supplies
1409         *                     defaults values for the TypedArray.  Can be
1410         *                     0 to not look for defaults.
1411         * @param defStyleRes A resource identifier of a style resource that
1412         *                    supplies default values for the TypedArray,
1413         *                    used only if defStyleAttr is 0 or can not be found
1414         *                    in the theme.  Can be 0 to not look for defaults.
1415         *
1416         * @return Returns a TypedArray holding an array of the attribute values.
1417         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1418         * when done with it.
1419         *
1420         * @see Resources#obtainAttributes
1421         * @see #obtainStyledAttributes(int[])
1422         * @see #obtainStyledAttributes(int, int[])
1423         */
1424        public TypedArray obtainStyledAttributes(AttributeSet set,
1425                int[] attrs, int defStyleAttr, int defStyleRes) {
1426            final int len = attrs.length;
1427            final TypedArray array = TypedArray.obtain(Resources.this, len);
1428
1429            // XXX note that for now we only work with compiled XML files.
1430            // To support generic XML files we will need to manually parse
1431            // out the attributes from the XML file (applying type information
1432            // contained in the resources and such).
1433            final XmlBlock.Parser parser = (XmlBlock.Parser)set;
1434            AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1435                    parser != null ? parser.mParseState : 0, attrs, array.mData, array.mIndices);
1436
1437            array.mTheme = this;
1438            array.mXml = parser;
1439
1440            if (false) {
1441                int[] data = array.mData;
1442
1443                System.out.println("Attributes:");
1444                String s = "  Attrs:";
1445                int i;
1446                for (i=0; i<set.getAttributeCount(); i++) {
1447                    s = s + " " + set.getAttributeName(i);
1448                    int id = set.getAttributeNameResource(i);
1449                    if (id != 0) {
1450                        s = s + "(0x" + Integer.toHexString(id) + ")";
1451                    }
1452                    s = s + "=" + set.getAttributeValue(i);
1453                }
1454                System.out.println(s);
1455                s = "  Found:";
1456                TypedValue value = new TypedValue();
1457                for (i=0; i<attrs.length; i++) {
1458                    int d = i*AssetManager.STYLE_NUM_ENTRIES;
1459                    value.type = data[d+AssetManager.STYLE_TYPE];
1460                    value.data = data[d+AssetManager.STYLE_DATA];
1461                    value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1462                    value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1463                    s = s + " 0x" + Integer.toHexString(attrs[i])
1464                        + "=" + value;
1465                }
1466                System.out.println(s);
1467            }
1468
1469            return array;
1470        }
1471
1472        /**
1473         * Retrieve the values for a set of attributes in the Theme. The
1474         * contents of the typed array are ultimately filled in by
1475         * {@link Resources#getValue}.
1476         *
1477         * @param values The base set of attribute values, must be equal
1478         *               in length to {@code attrs} or {@code null}. All values
1479         *               must be of type {@link TypedValue#TYPE_ATTRIBUTE}.
1480         * @param attrs The desired attributes to be retrieved.
1481         * @param defStyleAttr An attribute in the current theme that contains a
1482         *                     reference to a style resource that supplies
1483         *                     defaults values for the TypedArray.  Can be
1484         *                     0 to not look for defaults.
1485         * @param defStyleRes A resource identifier of a style resource that
1486         *                    supplies default values for the TypedArray,
1487         *                    used only if defStyleAttr is 0 or can not be found
1488         *                    in the theme.  Can be 0 to not look for defaults.
1489         * @return Returns a TypedArray holding an array of the attribute
1490         *         values. Be sure to call {@link TypedArray#recycle()}
1491         *         when done with it.
1492         * @hide
1493         */
1494        public TypedArray resolveAttributes(int[] values, int[] attrs,
1495                int defStyleAttr, int defStyleRes) {
1496            final int len = attrs.length;
1497            if (values != null && len != values.length) {
1498                throw new IllegalArgumentException(
1499                        "Base attribute values must be null or the same length as attrs");
1500            }
1501
1502            final TypedArray array = TypedArray.obtain(Resources.this, len);
1503            AssetManager.resolveAttrs(mTheme, defStyleAttr, defStyleRes,
1504                    values, attrs, array.mData, array.mIndices);
1505            array.mTheme = this;
1506            array.mXml = null;
1507
1508            return array;
1509        }
1510
1511        /**
1512         * Retrieve the value of an attribute in the Theme.  The contents of
1513         * <var>outValue</var> are ultimately filled in by
1514         * {@link Resources#getValue}.
1515         *
1516         * @param resid The resource identifier of the desired theme
1517         *              attribute.
1518         * @param outValue Filled in with the ultimate resource value supplied
1519         *                 by the attribute.
1520         * @param resolveRefs If true, resource references will be walked; if
1521         *                    false, <var>outValue</var> may be a
1522         *                    TYPE_REFERENCE.  In either case, it will never
1523         *                    be a TYPE_ATTRIBUTE.
1524         *
1525         * @return boolean Returns true if the attribute was found and
1526         *         <var>outValue</var> is valid, else false.
1527         */
1528        public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
1529            boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1530            if (false) {
1531                System.out.println(
1532                    "resolveAttribute #" + Integer.toHexString(resid)
1533                    + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type)
1534                    + ", data=0x" + Integer.toHexString(outValue.data));
1535            }
1536            return got;
1537        }
1538
1539        /**
1540         * Returns the resources to which this theme belongs.
1541         *
1542         * @return Resources to which this theme belongs.
1543         */
1544        public Resources getResources() {
1545            return Resources.this;
1546        }
1547
1548        /**
1549         * Return a drawable object associated with a particular resource ID
1550         * and styled for the Theme.
1551         *
1552         * @param id The desired resource identifier, as generated by the aapt
1553         *           tool. This integer encodes the package, type, and resource
1554         *           entry. The value 0 is an invalid identifier.
1555         * @return Drawable An object that can be used to draw this resource.
1556         * @throws NotFoundException Throws NotFoundException if the given ID
1557         *         does not exist.
1558         */
1559        public Drawable getDrawable(int id) throws NotFoundException {
1560            return Resources.this.getDrawable(id, this);
1561        }
1562
1563        /**
1564         * Print contents of this theme out to the log.  For debugging only.
1565         *
1566         * @param priority The log priority to use.
1567         * @param tag The log tag to use.
1568         * @param prefix Text to prefix each line printed.
1569         */
1570        public void dump(int priority, String tag, String prefix) {
1571            AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1572        }
1573
1574        @Override
1575        protected void finalize() throws Throwable {
1576            super.finalize();
1577            mAssets.releaseTheme(mTheme);
1578        }
1579
1580        /*package*/ Theme() {
1581            mAssets = Resources.this.mAssets;
1582            mTheme = mAssets.createTheme();
1583        }
1584
1585        @SuppressWarnings("hiding")
1586        private final AssetManager mAssets;
1587        private final long mTheme;
1588
1589        /** Resource identifier for the theme. */
1590        private int mThemeResId = 0;
1591
1592        // Needed by layoutlib.
1593        /*package*/ long getNativeTheme() {
1594            return mTheme;
1595        }
1596
1597        /*package*/ int getAppliedStyleResId() {
1598            return mThemeResId;
1599        }
1600    }
1601
1602    /**
1603     * Generate a new Theme object for this set of Resources.  It initially
1604     * starts out empty.
1605     *
1606     * @return Theme The newly created Theme container.
1607     */
1608    public final Theme newTheme() {
1609        return new Theme();
1610    }
1611
1612    /**
1613     * Retrieve a set of basic attribute values from an AttributeSet, not
1614     * performing styling of them using a theme and/or style resources.
1615     *
1616     * @param set The current attribute values to retrieve.
1617     * @param attrs The specific attributes to be retrieved.
1618     * @return Returns a TypedArray holding an array of the attribute values.
1619     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1620     * when done with it.
1621     *
1622     * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1623     */
1624    public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1625        int len = attrs.length;
1626        TypedArray array = TypedArray.obtain(this, len);
1627
1628        // XXX note that for now we only work with compiled XML files.
1629        // To support generic XML files we will need to manually parse
1630        // out the attributes from the XML file (applying type information
1631        // contained in the resources and such).
1632        XmlBlock.Parser parser = (XmlBlock.Parser)set;
1633        mAssets.retrieveAttributes(parser.mParseState, attrs,
1634                array.mData, array.mIndices);
1635
1636        array.mXml = parser;
1637
1638        return array;
1639    }
1640
1641    /**
1642     * Store the newly updated configuration.
1643     */
1644    public void updateConfiguration(Configuration config,
1645            DisplayMetrics metrics) {
1646        updateConfiguration(config, metrics, null);
1647    }
1648
1649    /**
1650     * @hide
1651     */
1652    public void updateConfiguration(Configuration config,
1653            DisplayMetrics metrics, CompatibilityInfo compat) {
1654        synchronized (mAccessLock) {
1655            if (false) {
1656                Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1657                        + mConfiguration + " old compat is " + mCompatibilityInfo);
1658                Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1659                        + config + " new compat is " + compat);
1660            }
1661            if (compat != null) {
1662                mCompatibilityInfo = compat;
1663            }
1664            if (metrics != null) {
1665                mMetrics.setTo(metrics);
1666            }
1667            // NOTE: We should re-arrange this code to create a Display
1668            // with the CompatibilityInfo that is used everywhere we deal
1669            // with the display in relation to this app, rather than
1670            // doing the conversion here.  This impl should be okay because
1671            // we make sure to return a compatible display in the places
1672            // where there are public APIs to retrieve the display...  but
1673            // it would be cleaner and more maintainble to just be
1674            // consistently dealing with a compatible display everywhere in
1675            // the framework.
1676            mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1677
1678            int configChanges = 0xfffffff;
1679            if (config != null) {
1680                mTmpConfig.setTo(config);
1681                int density = config.densityDpi;
1682                if (density == Configuration.DENSITY_DPI_UNDEFINED) {
1683                    density = mMetrics.noncompatDensityDpi;
1684                }
1685
1686                mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
1687
1688                if (mTmpConfig.locale == null) {
1689                    mTmpConfig.locale = Locale.getDefault();
1690                    mTmpConfig.setLayoutDirection(mTmpConfig.locale);
1691                }
1692                configChanges = mConfiguration.updateFrom(mTmpConfig);
1693                configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
1694            }
1695            if (mConfiguration.locale == null) {
1696                mConfiguration.locale = Locale.getDefault();
1697                mConfiguration.setLayoutDirection(mConfiguration.locale);
1698            }
1699            if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1700                mMetrics.densityDpi = mConfiguration.densityDpi;
1701                mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1702            }
1703            mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
1704
1705            String locale = null;
1706            if (mConfiguration.locale != null) {
1707                locale = adjustLanguageTag(localeToLanguageTag(mConfiguration.locale));
1708            }
1709            int width, height;
1710            if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1711                width = mMetrics.widthPixels;
1712                height = mMetrics.heightPixels;
1713            } else {
1714                //noinspection SuspiciousNameCombination
1715                width = mMetrics.heightPixels;
1716                //noinspection SuspiciousNameCombination
1717                height = mMetrics.widthPixels;
1718            }
1719            int keyboardHidden = mConfiguration.keyboardHidden;
1720            if (keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1721                    && mConfiguration.hardKeyboardHidden
1722                            == Configuration.HARDKEYBOARDHIDDEN_YES) {
1723                keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
1724            }
1725            mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
1726                    locale, mConfiguration.orientation,
1727                    mConfiguration.touchscreen,
1728                    mConfiguration.densityDpi, mConfiguration.keyboard,
1729                    keyboardHidden, mConfiguration.navigation, width, height,
1730                    mConfiguration.smallestScreenWidthDp,
1731                    mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
1732                    mConfiguration.screenLayout, mConfiguration.uiMode,
1733                    Build.VERSION.RESOURCES_SDK_INT);
1734
1735            if (DEBUG_CONFIG) {
1736                Slog.i(TAG, "**** Updating config of " + this + ": final config is " + mConfiguration
1737                        + " final compat is " + mCompatibilityInfo);
1738            }
1739
1740            clearDrawableCachesLocked(mDrawableCache, configChanges);
1741            clearDrawableCachesLocked(mColorDrawableCache, configChanges);
1742
1743            mColorStateListCache.clear();
1744
1745            flushLayoutCache();
1746        }
1747        synchronized (sSync) {
1748            if (mPluralRule != null) {
1749                mPluralRule = NativePluralRules.forLocale(config.locale);
1750            }
1751        }
1752    }
1753
1754    private void clearDrawableCachesLocked(
1755            ThemedCaches<ConstantState> caches, int configChanges) {
1756        final int N = caches.size();
1757        for (int i = 0; i < N; i++) {
1758            clearDrawableCacheLocked(caches.valueAt(i), configChanges);
1759        }
1760    }
1761
1762    private void clearDrawableCacheLocked(
1763            LongSparseArray<WeakReference<ConstantState>> cache, int configChanges) {
1764        if (DEBUG_CONFIG) {
1765            Log.d(TAG, "Cleaning up drawables config changes: 0x"
1766                    + Integer.toHexString(configChanges));
1767        }
1768        final int N = cache.size();
1769        for (int i = 0; i < N; i++) {
1770            final WeakReference<ConstantState> ref = cache.valueAt(i);
1771            if (ref != null) {
1772                final ConstantState cs = ref.get();
1773                if (cs != null) {
1774                    if (Configuration.needNewResources(
1775                            configChanges, cs.getChangingConfigurations())) {
1776                        if (DEBUG_CONFIG) {
1777                            Log.d(TAG, "FLUSHING #0x"
1778                                    + Long.toHexString(mDrawableCache.keyAt(i))
1779                                    + " / " + cs + " with changes: 0x"
1780                                    + Integer.toHexString(cs.getChangingConfigurations()));
1781                        }
1782                        cache.setValueAt(i, null);
1783                    } else if (DEBUG_CONFIG) {
1784                        Log.d(TAG, "(Keeping #0x"
1785                                + Long.toHexString(cache.keyAt(i))
1786                                + " / " + cs + " with changes: 0x"
1787                                + Integer.toHexString(cs.getChangingConfigurations())
1788                                + ")");
1789                    }
1790                }
1791            }
1792        }
1793    }
1794
1795    // Locale.toLanguageTag() is not available in Java6. LayoutLib overrides
1796    // this method to enable users to use Java6.
1797    private String localeToLanguageTag(Locale locale) {
1798        return locale.toLanguageTag();
1799    }
1800
1801    /**
1802     * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
1803     * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
1804     *
1805     * All released versions of android prior to "L" used the deprecated language
1806     * tags, so we will need to support them for backwards compatibility.
1807     *
1808     * Note that this conversion needs to take place *after* the call to
1809     * {@code toLanguageTag} because that will convert all the deprecated codes to
1810     * the new ones, even if they're set manually.
1811     */
1812    private static String adjustLanguageTag(String languageTag) {
1813        final int separator = languageTag.indexOf('-');
1814        final String language;
1815        final String remainder;
1816
1817        if (separator == -1) {
1818            language = languageTag;
1819            remainder = "";
1820        } else {
1821            language = languageTag.substring(0, separator);
1822            remainder = languageTag.substring(separator);
1823        }
1824
1825        if ("id".equals(language)) {
1826            return "in" + remainder;
1827        } else if ("yi".equals(language)) {
1828            return "ji" + remainder;
1829        } else if ("he".equals(language)) {
1830            return "iw" + remainder;
1831        } else {
1832            return languageTag;
1833        }
1834    }
1835
1836    /**
1837     * Update the system resources configuration if they have previously
1838     * been initialized.
1839     *
1840     * @hide
1841     */
1842    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
1843            CompatibilityInfo compat) {
1844        if (mSystem != null) {
1845            mSystem.updateConfiguration(config, metrics, compat);
1846            //Log.i(TAG, "Updated system resources " + mSystem
1847            //        + ": " + mSystem.getConfiguration());
1848        }
1849    }
1850
1851    /**
1852     * Return the current display metrics that are in effect for this resource
1853     * object.  The returned object should be treated as read-only.
1854     *
1855     * @return The resource's current display metrics.
1856     */
1857    public DisplayMetrics getDisplayMetrics() {
1858        if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
1859                + "x" + mMetrics.heightPixels + " " + mMetrics.density);
1860        return mMetrics;
1861    }
1862
1863    /**
1864     * Return the current configuration that is in effect for this resource
1865     * object.  The returned object should be treated as read-only.
1866     *
1867     * @return The resource's current configuration.
1868     */
1869    public Configuration getConfiguration() {
1870        return mConfiguration;
1871    }
1872
1873    /**
1874     * Return the compatibility mode information for the application.
1875     * The returned object should be treated as read-only.
1876     *
1877     * @return compatibility info.
1878     * @hide
1879     */
1880    public CompatibilityInfo getCompatibilityInfo() {
1881        return mCompatibilityInfo;
1882    }
1883
1884    /**
1885     * This is just for testing.
1886     * @hide
1887     */
1888    public void setCompatibilityInfo(CompatibilityInfo ci) {
1889        if (ci != null) {
1890            mCompatibilityInfo = ci;
1891            updateConfiguration(mConfiguration, mMetrics);
1892        }
1893    }
1894
1895    /**
1896     * Return a resource identifier for the given resource name.  A fully
1897     * qualified resource name is of the form "package:type/entry".  The first
1898     * two components (package and type) are optional if defType and
1899     * defPackage, respectively, are specified here.
1900     *
1901     * <p>Note: use of this function is discouraged.  It is much more
1902     * efficient to retrieve resources by identifier than by name.
1903     *
1904     * @param name The name of the desired resource.
1905     * @param defType Optional default resource type to find, if "type/" is
1906     *                not included in the name.  Can be null to require an
1907     *                explicit type.
1908     * @param defPackage Optional default package to find, if "package:" is
1909     *                   not included in the name.  Can be null to require an
1910     *                   explicit package.
1911     *
1912     * @return int The associated resource identifier.  Returns 0 if no such
1913     *         resource was found.  (0 is not a valid resource ID.)
1914     */
1915    public int getIdentifier(String name, String defType, String defPackage) {
1916        if (name == null) {
1917            throw new NullPointerException("name is null");
1918        }
1919        try {
1920            return Integer.parseInt(name);
1921        } catch (Exception e) {
1922            // Ignore
1923        }
1924        return mAssets.getResourceIdentifier(name, defType, defPackage);
1925    }
1926
1927    /**
1928     * Return true if given resource identifier includes a package.
1929     *
1930     * @hide
1931     */
1932    public static boolean resourceHasPackage(int resid) {
1933        return (resid >>> 24) != 0;
1934    }
1935
1936    /**
1937     * Return the full name for a given resource identifier.  This name is
1938     * a single string of the form "package:type/entry".
1939     *
1940     * @param resid The resource identifier whose name is to be retrieved.
1941     *
1942     * @return A string holding the name of the resource.
1943     *
1944     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1945     *
1946     * @see #getResourcePackageName
1947     * @see #getResourceTypeName
1948     * @see #getResourceEntryName
1949     */
1950    public String getResourceName(int resid) throws NotFoundException {
1951        String str = mAssets.getResourceName(resid);
1952        if (str != null) return str;
1953        throw new NotFoundException("Unable to find resource ID #0x"
1954                + Integer.toHexString(resid));
1955    }
1956
1957    /**
1958     * Return the package name for a given resource identifier.
1959     *
1960     * @param resid The resource identifier whose package name is to be
1961     * retrieved.
1962     *
1963     * @return A string holding the package name of the resource.
1964     *
1965     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1966     *
1967     * @see #getResourceName
1968     */
1969    public String getResourcePackageName(int resid) throws NotFoundException {
1970        String str = mAssets.getResourcePackageName(resid);
1971        if (str != null) return str;
1972        throw new NotFoundException("Unable to find resource ID #0x"
1973                + Integer.toHexString(resid));
1974    }
1975
1976    /**
1977     * Return the type name for a given resource identifier.
1978     *
1979     * @param resid The resource identifier whose type name is to be
1980     * retrieved.
1981     *
1982     * @return A string holding the type name of the resource.
1983     *
1984     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1985     *
1986     * @see #getResourceName
1987     */
1988    public String getResourceTypeName(int resid) throws NotFoundException {
1989        String str = mAssets.getResourceTypeName(resid);
1990        if (str != null) return str;
1991        throw new NotFoundException("Unable to find resource ID #0x"
1992                + Integer.toHexString(resid));
1993    }
1994
1995    /**
1996     * Return the entry name for a given resource identifier.
1997     *
1998     * @param resid The resource identifier whose entry name is to be
1999     * retrieved.
2000     *
2001     * @return A string holding the entry name of the resource.
2002     *
2003     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2004     *
2005     * @see #getResourceName
2006     */
2007    public String getResourceEntryName(int resid) throws NotFoundException {
2008        String str = mAssets.getResourceEntryName(resid);
2009        if (str != null) return str;
2010        throw new NotFoundException("Unable to find resource ID #0x"
2011                + Integer.toHexString(resid));
2012    }
2013
2014    /**
2015     * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2016     * an XML file.  You call this when you are at the parent tag of the
2017     * extra tags, and it will return once all of the child tags have been parsed.
2018     * This will call {@link #parseBundleExtra} for each extra tag encountered.
2019     *
2020     * @param parser The parser from which to retrieve the extras.
2021     * @param outBundle A Bundle in which to place all parsed extras.
2022     * @throws XmlPullParserException
2023     * @throws IOException
2024     */
2025    public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2026            throws XmlPullParserException, IOException {
2027        int outerDepth = parser.getDepth();
2028        int type;
2029        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2030               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2031            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2032                continue;
2033            }
2034
2035            String nodeName = parser.getName();
2036            if (nodeName.equals("extra")) {
2037                parseBundleExtra("extra", parser, outBundle);
2038                XmlUtils.skipCurrentTag(parser);
2039
2040            } else {
2041                XmlUtils.skipCurrentTag(parser);
2042            }
2043        }
2044    }
2045
2046    /**
2047     * Parse a name/value pair out of an XML tag holding that data.  The
2048     * AttributeSet must be holding the data defined by
2049     * {@link android.R.styleable#Extra}.  The following value types are supported:
2050     * <ul>
2051     * <li> {@link TypedValue#TYPE_STRING}:
2052     * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2053     * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2054     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2055     * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2056     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2057     * <li> {@link TypedValue#TYPE_FLOAT}:
2058     * {@link Bundle#putCharSequence Bundle.putFloat()}
2059     * </ul>
2060     *
2061     * @param tagName The name of the tag these attributes come from; this is
2062     * only used for reporting error messages.
2063     * @param attrs The attributes from which to retrieve the name/value pair.
2064     * @param outBundle The Bundle in which to place the parsed value.
2065     * @throws XmlPullParserException If the attributes are not valid.
2066     */
2067    public void parseBundleExtra(String tagName, AttributeSet attrs,
2068            Bundle outBundle) throws XmlPullParserException {
2069        TypedArray sa = obtainAttributes(attrs,
2070                com.android.internal.R.styleable.Extra);
2071
2072        String name = sa.getString(
2073                com.android.internal.R.styleable.Extra_name);
2074        if (name == null) {
2075            sa.recycle();
2076            throw new XmlPullParserException("<" + tagName
2077                    + "> requires an android:name attribute at "
2078                    + attrs.getPositionDescription());
2079        }
2080
2081        TypedValue v = sa.peekValue(
2082                com.android.internal.R.styleable.Extra_value);
2083        if (v != null) {
2084            if (v.type == TypedValue.TYPE_STRING) {
2085                CharSequence cs = v.coerceToString();
2086                outBundle.putCharSequence(name, cs);
2087            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2088                outBundle.putBoolean(name, v.data != 0);
2089            } else if (v.type >= TypedValue.TYPE_FIRST_INT
2090                    && v.type <= TypedValue.TYPE_LAST_INT) {
2091                outBundle.putInt(name, v.data);
2092            } else if (v.type == TypedValue.TYPE_FLOAT) {
2093                outBundle.putFloat(name, v.getFloat());
2094            } else {
2095                sa.recycle();
2096                throw new XmlPullParserException("<" + tagName
2097                        + "> only supports string, integer, float, color, and boolean at "
2098                        + attrs.getPositionDescription());
2099            }
2100        } else {
2101            sa.recycle();
2102            throw new XmlPullParserException("<" + tagName
2103                    + "> requires an android:value or android:resource attribute at "
2104                    + attrs.getPositionDescription());
2105        }
2106
2107        sa.recycle();
2108    }
2109
2110    /**
2111     * Retrieve underlying AssetManager storage for these resources.
2112     */
2113    public final AssetManager getAssets() {
2114        return mAssets;
2115    }
2116
2117    /**
2118     * Call this to remove all cached loaded layout resources from the
2119     * Resources object.  Only intended for use with performance testing
2120     * tools.
2121     */
2122    public final void flushLayoutCache() {
2123        synchronized (mCachedXmlBlockIds) {
2124            // First see if this block is in our cache.
2125            final int num = mCachedXmlBlockIds.length;
2126            for (int i=0; i<num; i++) {
2127                mCachedXmlBlockIds[i] = -0;
2128                XmlBlock oldBlock = mCachedXmlBlocks[i];
2129                if (oldBlock != null) {
2130                    oldBlock.close();
2131                }
2132                mCachedXmlBlocks[i] = null;
2133            }
2134        }
2135    }
2136
2137    /**
2138     * Start preloading of resource data using this Resources object.  Only
2139     * for use by the zygote process for loading common system resources.
2140     * {@hide}
2141     */
2142    public final void startPreloading() {
2143        synchronized (sSync) {
2144            if (sPreloaded) {
2145                throw new IllegalStateException("Resources already preloaded");
2146            }
2147            sPreloaded = true;
2148            mPreloading = true;
2149            sPreloadedDensity = DisplayMetrics.DENSITY_DEVICE;
2150            mConfiguration.densityDpi = sPreloadedDensity;
2151            updateConfiguration(null, null);
2152        }
2153    }
2154
2155    /**
2156     * Called by zygote when it is done preloading resources, to change back
2157     * to normal Resources operation.
2158     */
2159    public final void finishPreloading() {
2160        if (mPreloading) {
2161            mPreloading = false;
2162            flushLayoutCache();
2163        }
2164    }
2165
2166    /**
2167     * @hide
2168     */
2169    public LongSparseArray<ConstantState> getPreloadedDrawables() {
2170        return sPreloadedDrawables[0];
2171    }
2172
2173    private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2174            int resourceId, String name) {
2175        // We allow preloading of resources even if they vary by font scale (which
2176        // doesn't impact resource selection) or density (which we handle specially by
2177        // simply turning off all preloading), as well as any other configs specified
2178        // by the caller.
2179        if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
2180                ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
2181            String resName;
2182            try {
2183                resName = getResourceName(resourceId);
2184            } catch (NotFoundException e) {
2185                resName = "?";
2186            }
2187            // This should never happen in production, so we should log a
2188            // warning even if we're not debugging.
2189            Log.w(TAG, "Preloaded " + name + " resource #0x"
2190                    + Integer.toHexString(resourceId)
2191                    + " (" + resName + ") that varies with configuration!!");
2192            return false;
2193        }
2194        if (TRACE_FOR_PRELOAD) {
2195            String resName;
2196            try {
2197                resName = getResourceName(resourceId);
2198            } catch (NotFoundException e) {
2199                resName = "?";
2200            }
2201            Log.w(TAG, "Preloading " + name + " resource #0x"
2202                    + Integer.toHexString(resourceId)
2203                    + " (" + resName + ")");
2204        }
2205        return true;
2206    }
2207
2208    /*package*/ Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
2209        if (TRACE_FOR_PRELOAD) {
2210            // Log only framework resources
2211            if ((id >>> 24) == 0x1) {
2212                final String name = getResourceName(id);
2213                if (name != null) {
2214                    Log.d("PreloadDrawable", name);
2215                }
2216            }
2217        }
2218
2219        final boolean isColorDrawable;
2220        final ThemedCaches<ConstantState> caches;
2221        final long key;
2222        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2223                && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2224            isColorDrawable = true;
2225            caches = mColorDrawableCache;
2226            key = value.data;
2227        } else {
2228            isColorDrawable = false;
2229            caches = mDrawableCache;
2230            key = (((long) value.assetCookie) << 32) | value.data;
2231        }
2232
2233        // First, check whether we have a cached version of this drawable
2234        // that's valid for the specified theme. This may apply a theme to a
2235        // cached drawable that has themeable attributes but was not previously
2236        // themed.
2237        if (!mPreloading) {
2238            final Drawable cachedDrawable = getCachedDrawable(caches, key, theme);
2239            if (cachedDrawable != null) {
2240                return cachedDrawable;
2241            }
2242        }
2243
2244        // Next, check preloaded drawables. These are unthemed but may have
2245        // themeable attributes.
2246        final ConstantState cs;
2247        if (isColorDrawable) {
2248            cs = sPreloadedColorDrawables.get(key);
2249        } else {
2250            cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2251        }
2252
2253        final Drawable dr;
2254        if (cs != null) {
2255            dr = cs.newDrawable(this, theme);
2256        } else if (isColorDrawable) {
2257            dr = new ColorDrawable(value.data);
2258        } else {
2259            dr = loadDrawableForCookie(value, id, theme);
2260        }
2261
2262        // If we were able to obtain a drawable, attempt to place it in the
2263        // appropriate cache (e.g. no theme, themed, themeable).
2264        if (dr != null) {
2265            dr.setChangingConfigurations(value.changingConfigurations);
2266            cacheDrawable(value, theme, isColorDrawable, caches, key, dr);
2267        }
2268
2269        return dr;
2270    }
2271
2272    private void cacheDrawable(TypedValue value, Theme theme, boolean isColorDrawable,
2273            ThemedCaches<ConstantState> caches, long key, Drawable dr) {
2274        final ConstantState cs = dr.getConstantState();
2275        if (cs == null) {
2276            return;
2277        }
2278
2279        if (mPreloading) {
2280            // Preloaded drawables never have a theme, but may be themeable.
2281            final int changingConfigs = cs.getChangingConfigurations();
2282            if (isColorDrawable) {
2283                if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2284                    sPreloadedColorDrawables.put(key, cs);
2285                }
2286            } else {
2287                if (verifyPreloadConfig(
2288                        changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2289                    if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2290                        // If this resource does not vary based on layout direction,
2291                        // we can put it in all of the preload maps.
2292                        sPreloadedDrawables[0].put(key, cs);
2293                        sPreloadedDrawables[1].put(key, cs);
2294                    } else {
2295                        // Otherwise, only in the layout dir we loaded it for.
2296                        sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2297                    }
2298                }
2299            }
2300        } else {
2301            synchronized (mAccessLock) {
2302                final LongSparseArray<WeakReference<ConstantState>> themedCache;
2303                themedCache = caches.getOrCreate(theme == null ? 0 : theme.mThemeResId);
2304                themedCache.put(key, new WeakReference<ConstantState>(cs));
2305            }
2306        }
2307    }
2308
2309    /**
2310     * Loads a drawable from XML or resources stream.
2311     */
2312    private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2313        if (value.string == null) {
2314            throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
2315                    + Integer.toHexString(id) + ")  is not a Drawable (color or path): " + value);
2316        }
2317
2318        final String file = value.string.toString();
2319
2320        if (TRACE_FOR_MISS_PRELOAD) {
2321            // Log only framework resources
2322            if ((id >>> 24) == 0x1) {
2323                final String name = getResourceName(id);
2324                if (name != null) {
2325                    Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2326                            + ": " + name + " at " + file);
2327                }
2328            }
2329        }
2330
2331        if (DEBUG_LOAD) {
2332            Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2333        }
2334
2335        final Drawable dr;
2336
2337        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2338        try {
2339            if (file.endsWith(".xml")) {
2340                final XmlResourceParser rp = loadXmlResourceParser(
2341                        file, id, value.assetCookie, "drawable");
2342                dr = Drawable.createFromXmlThemed(this, rp, theme);
2343                rp.close();
2344            } else {
2345                final InputStream is = mAssets.openNonAsset(
2346                        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
2347                dr = Drawable.createFromResourceStreamThemed(this, value, is, file, null, theme);
2348                is.close();
2349            }
2350        } catch (Exception e) {
2351            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2352            final NotFoundException rnf = new NotFoundException(
2353                    "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2354            rnf.initCause(e);
2355            throw rnf;
2356        }
2357        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2358
2359        return dr;
2360    }
2361
2362    private Drawable getCachedDrawable(ThemedCaches<ConstantState> caches, long key, Theme theme) {
2363        synchronized (mAccessLock) {
2364            final int themeKey = theme != null ? theme.mThemeResId : 0;
2365            final LongSparseArray<WeakReference<ConstantState>> themedCache = caches.get(themeKey);
2366            if (themedCache != null) {
2367                final Drawable themedDrawable = getCachedDrawableLocked(themedCache, key);
2368                if (themedDrawable != null) {
2369                    return themedDrawable;
2370                }
2371            }
2372
2373            // No cached drawable, we'll need to create a new one.
2374            return null;
2375        }
2376    }
2377
2378    private ConstantState getConstantStateLocked(
2379            LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) {
2380        final WeakReference<ConstantState> wr = drawableCache.get(key);
2381        if (wr != null) {   // we have the key
2382            final ConstantState entry = wr.get();
2383            if (entry != null) {
2384                //Log.i(TAG, "Returning cached drawable @ #" +
2385                //        Integer.toHexString(((Integer)key).intValue())
2386                //        + " in " + this + ": " + entry);
2387                return entry;
2388            } else {  // our entry has been purged
2389                drawableCache.delete(key);
2390            }
2391        }
2392        return null;
2393    }
2394
2395    private Drawable getCachedDrawableLocked(
2396            LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) {
2397        final ConstantState entry = getConstantStateLocked(drawableCache, key);
2398        if (entry != null) {
2399            return entry.newDrawable(this);
2400        }
2401        return null;
2402    }
2403
2404    /*package*/ ColorStateList loadColorStateList(TypedValue value, int id)
2405            throws NotFoundException {
2406        if (TRACE_FOR_PRELOAD) {
2407            // Log only framework resources
2408            if ((id >>> 24) == 0x1) {
2409                final String name = getResourceName(id);
2410                if (name != null) android.util.Log.d("PreloadColorStateList", name);
2411            }
2412        }
2413
2414        final long key = (((long) value.assetCookie) << 32) | value.data;
2415
2416        ColorStateList csl;
2417
2418        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
2419                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2420
2421            csl = sPreloadedColorStateLists.get(key);
2422            if (csl != null) {
2423                return csl;
2424            }
2425
2426            csl = ColorStateList.valueOf(value.data);
2427            if (mPreloading) {
2428                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2429                        "color")) {
2430                    sPreloadedColorStateLists.put(key, csl);
2431                }
2432            }
2433
2434            return csl;
2435        }
2436
2437        csl = getCachedColorStateList(key);
2438        if (csl != null) {
2439            return csl;
2440        }
2441
2442        csl = sPreloadedColorStateLists.get(key);
2443        if (csl != null) {
2444            return csl;
2445        }
2446
2447        if (value.string == null) {
2448            throw new NotFoundException(
2449                    "Resource is not a ColorStateList (color or path): " + value);
2450        }
2451
2452        final String file = value.string.toString();
2453
2454        if (file.endsWith(".xml")) {
2455            Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2456            try {
2457                final XmlResourceParser rp = loadXmlResourceParser(
2458                        file, id, value.assetCookie, "colorstatelist");
2459                csl = ColorStateList.createFromXml(this, rp);
2460                rp.close();
2461            } catch (Exception e) {
2462                Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2463                NotFoundException rnf = new NotFoundException(
2464                    "File " + file + " from color state list resource ID #0x"
2465                    + Integer.toHexString(id));
2466                rnf.initCause(e);
2467                throw rnf;
2468            }
2469            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2470        } else {
2471            throw new NotFoundException(
2472                    "File " + file + " from drawable resource ID #0x"
2473                    + Integer.toHexString(id) + ": .xml extension required");
2474        }
2475
2476        if (csl != null) {
2477            if (mPreloading) {
2478                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2479                        "color")) {
2480                    sPreloadedColorStateLists.put(key, csl);
2481                }
2482            } else {
2483                synchronized (mAccessLock) {
2484                    //Log.i(TAG, "Saving cached color state list @ #" +
2485                    //        Integer.toHexString(key.intValue())
2486                    //        + " in " + this + ": " + csl);
2487                    mColorStateListCache.put(key, new WeakReference<ColorStateList>(csl));
2488                }
2489            }
2490        }
2491
2492        return csl;
2493    }
2494
2495    private ColorStateList getCachedColorStateList(long key) {
2496        synchronized (mAccessLock) {
2497            WeakReference<ColorStateList> wr = mColorStateListCache.get(key);
2498            if (wr != null) {   // we have the key
2499                ColorStateList entry = wr.get();
2500                if (entry != null) {
2501                    //Log.i(TAG, "Returning cached color state list @ #" +
2502                    //        Integer.toHexString(((Integer)key).intValue())
2503                    //        + " in " + this + ": " + entry);
2504                    return entry;
2505                } else {  // our entry has been purged
2506                    mColorStateListCache.delete(key);
2507                }
2508            }
2509        }
2510        return null;
2511    }
2512
2513    /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type)
2514            throws NotFoundException {
2515        synchronized (mAccessLock) {
2516            TypedValue value = mTmpValue;
2517            if (value == null) {
2518                mTmpValue = value = new TypedValue();
2519            }
2520            getValue(id, value, true);
2521            if (value.type == TypedValue.TYPE_STRING) {
2522                return loadXmlResourceParser(value.string.toString(), id,
2523                        value.assetCookie, type);
2524            }
2525            throw new NotFoundException(
2526                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
2527                    + Integer.toHexString(value.type) + " is not valid");
2528        }
2529    }
2530
2531    /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id,
2532            int assetCookie, String type) throws NotFoundException {
2533        if (id != 0) {
2534            try {
2535                // These may be compiled...
2536                synchronized (mCachedXmlBlockIds) {
2537                    // First see if this block is in our cache.
2538                    final int num = mCachedXmlBlockIds.length;
2539                    for (int i=0; i<num; i++) {
2540                        if (mCachedXmlBlockIds[i] == id) {
2541                            //System.out.println("**** REUSING XML BLOCK!  id="
2542                            //                   + id + ", index=" + i);
2543                            return mCachedXmlBlocks[i].newParser();
2544                        }
2545                    }
2546
2547                    // Not in the cache, create a new block and put it at
2548                    // the next slot in the cache.
2549                    XmlBlock block = mAssets.openXmlBlockAsset(
2550                            assetCookie, file);
2551                    if (block != null) {
2552                        int pos = mLastCachedXmlBlockIndex+1;
2553                        if (pos >= num) pos = 0;
2554                        mLastCachedXmlBlockIndex = pos;
2555                        XmlBlock oldBlock = mCachedXmlBlocks[pos];
2556                        if (oldBlock != null) {
2557                            oldBlock.close();
2558                        }
2559                        mCachedXmlBlockIds[pos] = id;
2560                        mCachedXmlBlocks[pos] = block;
2561                        //System.out.println("**** CACHING NEW XML BLOCK!  id="
2562                        //                   + id + ", index=" + pos);
2563                        return block.newParser();
2564                    }
2565                }
2566            } catch (Exception e) {
2567                NotFoundException rnf = new NotFoundException(
2568                        "File " + file + " from xml type " + type + " resource ID #0x"
2569                        + Integer.toHexString(id));
2570                rnf.initCause(e);
2571                throw rnf;
2572            }
2573        }
2574
2575        throw new NotFoundException(
2576                "File " + file + " from xml type " + type + " resource ID #0x"
2577                + Integer.toHexString(id));
2578    }
2579
2580    /*package*/ void recycleCachedStyledAttributes(TypedArray attrs) {
2581        synchronized (mAccessLock) {
2582            final TypedArray cached = mCachedStyledAttributes;
2583            if (cached == null || cached.mData.length < attrs.mData.length) {
2584                mCachedStyledAttributes = attrs;
2585            }
2586        }
2587    }
2588
2589    private Resources() {
2590        mAssets = AssetManager.getSystem();
2591        // NOTE: Intentionally leaving this uninitialized (all values set
2592        // to zero), so that anyone who tries to do something that requires
2593        // metrics will get a very wrong value.
2594        mConfiguration.setToDefaults();
2595        mMetrics.setToDefaults();
2596        updateConfiguration(null, null);
2597        mAssets.ensureStringBlocks();
2598    }
2599
2600    static class ThemedCaches<T> extends SparseArray<LongSparseArray<WeakReference<T>>> {
2601        /**
2602         * Returns the cache of drawables styled for the specified theme.
2603         * <p>
2604         * Drawables that have themeable attributes but were loaded without
2605         * specifying a theme are cached at themeResId = 0.
2606         */
2607        public LongSparseArray<WeakReference<T>> getOrCreate(int themeResId) {
2608            LongSparseArray<WeakReference<T>> result = get(themeResId);
2609            if (result == null) {
2610                result = new LongSparseArray<WeakReference<T>>(1);
2611                put(themeResId, result);
2612            }
2613            return result;
2614        }
2615    }
2616}
2617