FileDocCategorySizeDatePackage
Resources.javaAPI DocAndroid 1.5 API77767Wed May 06 22:41:54 BST 2009android.content.res

Resources

public class Resources extends Object
Class for accessing an application's resources. This sits on top of the asset manager of the application (accessible through getAssets()) and provides a higher-level API for getting typed data from the assets.

Fields Summary
static final String
TAG
private static final boolean
DEBUG_LOAD
private static final boolean
DEBUG_CONFIG
private static final boolean
TRACE_FOR_PRELOAD
private static final int
sSdkVersion
private static final Object
mSync
private static Resources
mSystem
private static final android.util.SparseArray
mPreloadedDrawables
private static final android.util.SparseArray
mPreloadedColorStateLists
private static boolean
mPreloaded
final android.util.TypedValue
mTmpValue
private final android.util.SparseArray
mDrawableCache
private final android.util.SparseArray
mColorStateListCache
private boolean
mPreloading
TypedArray
mCachedStyledAttributes
private int
mLastCachedXmlBlockIndex
private final int[]
mCachedXmlBlockIds
private final XmlBlock[]
mCachedXmlBlocks
final AssetManager
mAssets
private final Configuration
mConfiguration
final android.util.DisplayMetrics
mMetrics
PluralRules
mPluralRule
Constructors Summary
public Resources(AssetManager assets, android.util.DisplayMetrics metrics, Configuration config)
Create a new Resources object on top of an existing set of assets in an AssetManager.

param
assets Previously created AssetManager.
param
metrics Current display metrics to consider when selecting/computing resource values.
param
config Desired device configuration to consider when selecting/computing resource values (optional).

        mAssets = assets;
        mConfiguration.setToDefaults();
        mMetrics.setToDefaults();
        updateConfiguration(config, metrics);
        assets.ensureStringBlocks();
    
private Resources()

        mAssets = AssetManager.getSystem();
        // NOTE: Intentionally leaving this uninitialized (all values set
        // to zero), so that anyone who tries to do something that requires
        // metrics will get a very wrong value.
        mConfiguration.setToDefaults();
        mMetrics.setToDefaults();
        updateConfiguration(null, null);
        mAssets.ensureStringBlocks();
    
Methods Summary
public final voidfinishPreloading()
Called by zygote when it is done preloading resources, to change back to normal Resources operation.

        if (mPreloading) {
            mPreloading = false;
            flushLayoutCache();
        }
    
public final voidflushLayoutCache()
Call this to remove all cached loaded layout resources from the Resources object. Only intended for use with performance testing tools.

        synchronized (mCachedXmlBlockIds) {
            // First see if this block is in our cache.
            final int num = mCachedXmlBlockIds.length;
            for (int i=0; i<num; i++) {
                mCachedXmlBlockIds[i] = -0;
                XmlBlock oldBlock = mCachedXmlBlocks[i];
                if (oldBlock != null) {
                    oldBlock.close();
                }
                mCachedXmlBlocks[i] = null;
            }
        }
    
public XmlResourceParsergetAnimation(int id)
Return an XmlResourceParser through which you can read an animation description for the given resource ID. This parser has limited functionality -- in particular, you can't change its input, and only the high-level events are available.

This function is really a simple wrapper for calling {@link #getXml} with an animation resource.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
A new parser object through which you can read the XML data.
see
#getXml

        return loadXmlResourceParser(id, "anim");
    
public final AssetManagergetAssets()
Retrieve underlying AssetManager storage for these resources.

        return mAssets;
    
public booleangetBoolean(int id)
Return a boolean associated with a particular resource ID. This can be used with any integral resource value, and will return true if it is non-zero.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Returns the boolean value contained in the resource.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type >= TypedValue.TYPE_FIRST_INT
                && value.type <= TypedValue.TYPE_LAST_INT) {
                return value.data != 0;
            }
            throw new NotFoundException(
                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                + Integer.toHexString(value.type) + " is not valid");
        }
    
private ColorStateListgetCachedColorStateList(int key)

        synchronized (mTmpValue) {
            WeakReference<ColorStateList> wr = mColorStateListCache.get(key);
            if (wr != null) {   // we have the key
                ColorStateList entry = wr.get();
                if (entry != null) {
                    //Log.i(TAG, "Returning cached color state list @ #" +
                    //        Integer.toHexString(((Integer)key).intValue())
                    //        + " in " + this + ": " + entry);
                    return entry;
                }
                else {  // our entry has been purged
                    mColorStateListCache.delete(key);
                }
            }
        }
        return null;
    
private android.graphics.drawable.DrawablegetCachedDrawable(int key)

        synchronized (mTmpValue) {
            WeakReference<Drawable.ConstantState> wr = mDrawableCache.get(key);
            if (wr != null) {   // we have the key
                Drawable.ConstantState entry = wr.get();
                if (entry != null) {
                    //Log.i(TAG, "Returning cached drawable @ #" +
                    //        Integer.toHexString(((Integer)key).intValue())
                    //        + " in " + this + ": " + entry);
                    return entry.newDrawable();
                }
                else {  // our entry has been purged
                    mDrawableCache.delete(key);
                }
            }
        }
        return null;
    
private TypedArraygetCachedStyledAttributes(int len)

        synchronized (mTmpValue) {
            TypedArray attrs = mCachedStyledAttributes;
            if (attrs != null) {
                mCachedStyledAttributes = null;

                attrs.mLength = len;
                int fullLen = len * AssetManager.STYLE_NUM_ENTRIES;
                if (attrs.mData.length >= fullLen) {
                    return attrs;
                }
                attrs.mData = new int[fullLen];
                attrs.mIndices = new int[1+len];
                return attrs;
            }
            return new TypedArray(this,
                    new int[len*AssetManager.STYLE_NUM_ENTRIES],
                    new int[1+len], len);
        }
    
public intgetColor(int id)
Return a color integer associated with a particular resource ID. If the resource holds a complex {@link android.content.res.ColorStateList}, then the default color from the set is returned.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Returns a single color value in the form 0xAARRGGBB.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type >= TypedValue.TYPE_FIRST_INT
                && value.type <= TypedValue.TYPE_LAST_INT) {
                return value.data;
            } else if (value.type == TypedValue.TYPE_STRING) {
                ColorStateList csl = loadColorStateList(mTmpValue, id);
                return csl.getDefaultColor();
            }
            throw new NotFoundException(
                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                + Integer.toHexString(value.type) + " is not valid");
        }
    
public ColorStateListgetColorStateList(int id)
Return a color state list associated with a particular resource ID. The resource may contain either a single raw color value, or a complex {@link android.content.res.ColorStateList} holding multiple possible colors.

param
id The desired resource identifier of a {@link ColorStateList}, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Returns a ColorStateList object containing either a single solid color or multiple colors that can be selected based on a state.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            return loadColorStateList(value, id);
        }
    
public ConfigurationgetConfiguration()
Return the current configuration that is in effect for this resource object. The returned object should be treated as read-only.

return
The resource's current configuration.

        return mConfiguration;
    
public floatgetDimension(int id)
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current {@link DisplayMetrics} associated with the resources.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
return
Resource dimension value multiplied by the appropriate metric.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getDimensionPixelOffset
see
#getDimensionPixelSize

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type == TypedValue.TYPE_DIMENSION) {
                return TypedValue.complexToDimension(value.data, mMetrics);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    
public intgetDimensionPixelOffset(int id)
Retrieve a dimensional for a particular resource ID for use as an offset in raw pixels. This is the same as {@link #getDimension}, except the returned value is converted to integer pixels for you. An offset conversion involves simply truncating the base value to an integer.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
return
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getDimension
see
#getDimensionPixelSize

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type == TypedValue.TYPE_DIMENSION) {
                return TypedValue.complexToDimensionPixelOffset(
                        value.data, mMetrics);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    
public intgetDimensionPixelSize(int id)
Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as {@link #getDimension}, except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
return
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getDimension
see
#getDimensionPixelOffset

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type == TypedValue.TYPE_DIMENSION) {
                return TypedValue.complexToDimensionPixelSize(
                        value.data, mMetrics);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    
public android.util.DisplayMetricsgetDisplayMetrics()
Return the current display metrics that are in effect for this resource object. The returned object should be treated as read-only.

return
The resource's current display metrics.

        return mMetrics;
    
public android.graphics.drawable.DrawablegetDrawable(int id)
Return a drawable object associated with a particular resource ID. Various types of objects will be returned depending on the underlying resource -- for example, a solid color, PNG image, scalable image, etc. The Drawable API hides these implementation details.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Drawable An object that can be used to draw this resource.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            return loadDrawable(value, id);
        }
    
public floatgetFraction(int id, int base, int pbase)
Retrieve a fractional unit for a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
base The base value of this fraction. In other words, a standard fraction is multiplied by this value.
param
pbase The parent base value of this fraction. In other words, a parent fraction (nn%p) is multiplied by this value.
return
Attribute fractional value multiplied by the appropriate base value.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type == TypedValue.TYPE_FRACTION) {
                return TypedValue.complexToFraction(value.data, base, pbase);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    
public intgetIdentifier(java.lang.String name, java.lang.String defType, java.lang.String defPackage)
Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

param
name The name of the desired resource.
param
defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
param
defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
return
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)

        try {
            return Integer.parseInt(name);
        } catch (Exception e) {
            // Ignore
        }
        return mAssets.getResourceIdentifier(name, defType, defPackage);
    
public int[]getIntArray(int id)
Return the int array associated with a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
The int array associated with the resource.

        int[] res = mAssets.getArrayIntResource(id);
        if (res != null) {
            return res;
        }
        throw new NotFoundException("Int array resource ID #0x"
                                    + Integer.toHexString(id));
    
public intgetInteger(int id)
Return an integer associated with a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Returns the integer value contained in the resource.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type >= TypedValue.TYPE_FIRST_INT
                && value.type <= TypedValue.TYPE_LAST_INT) {
                return value.data;
            }
            throw new NotFoundException(
                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                + Integer.toHexString(value.type) + " is not valid");
        }
    
public XmlResourceParsergetLayout(int id)
Return an XmlResourceParser through which you can read a view layout description for the given resource ID. This parser has limited functionality -- in particular, you can't change its input, and only the high-level events are available.

This function is really a simple wrapper for calling {@link #getXml} with a layout resource.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
A new parser object through which you can read the XML data.
see
#getXml

        return loadXmlResourceParser(id, "layout");
    
public android.graphics.MoviegetMovie(int id)
Return a movie object associated with the particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        InputStream is = openRawResource(id);
        Movie movie = Movie.decodeStream(is);
        try {
            is.close();
        }
        catch (java.io.IOException e) {
            // don't care, since the return value is valid
        }
        return movie;
    
private PluralRulesgetPluralRule()

        synchronized (mSync) {
            if (mPluralRule == null) {
                mPluralRule = PluralRules.ruleForLocale(mConfiguration.locale);
            }
            return mPluralRule;
        }
    
public java.lang.StringgetQuantityString(int id, int quantity, java.lang.Object formatArgs)
Return the string value associated with a particular resource ID for a particular numerical quantity, substituting the format arguments as defined in {@link java.util.Formatter} and {@link java.lang.String#format}. It will be stripped of any styled text information. {@more}

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
quantity The number used to get the correct string for the current language's plural rules.
param
formatArgs The format arguments that will be used for substitution.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
String The string data associated with the resource, stripped of styled text information.

        String raw = getQuantityText(id, quantity).toString();
        return String.format(mConfiguration.locale, raw, formatArgs);
    
public java.lang.StringgetQuantityString(int id, int quantity)
Return the string value associated with a particular resource ID for a particular numerical quantity.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
quantity The number used to get the correct string for the current language's plural rules.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
String The string data associated with the resource, stripped of styled text information.

        return getQuantityText(id, quantity).toString();
    
public java.lang.CharSequencegetQuantityText(int id, int quantity)

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
CharSequence The string data associated with the resource, plus possibly styled text information.

        PluralRules rule = getPluralRule();
        CharSequence res = mAssets.getResourceBagText(id, rule.attrForNumber(quantity));
        if (res != null) {
            return res;
        }
        res = mAssets.getResourceBagText(id, PluralRules.ID_OTHER);
        if (res != null) {
            return res;
        }
        throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
                + " quantity=" + quantity
                + " item=" + PluralRules.stringForQuantity(rule.quantityForNumber(quantity)));
    
public java.lang.StringgetResourceEntryName(int resid)
Return the entry name for a given resource identifier.

param
resid The resource identifier whose entry name is to be retrieved.
return
A string holding the entry name of the resource.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getResourceName

        String str = mAssets.getResourceEntryName(resid);
        if (str != null) return str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    
public java.lang.StringgetResourceName(int resid)
Return the full name for a given resource identifier. This name is a single string of the form "package:type/entry".

param
resid The resource identifier whose name is to be retrieved.
return
A string holding the name of the resource.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getResourcePackageName
see
#getResourceTypeName
see
#getResourceEntryName

        String str = mAssets.getResourceName(resid);
        if (str != null) return str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    
public java.lang.StringgetResourcePackageName(int resid)
Return the package name for a given resource identifier.

param
resid The resource identifier whose package name is to be retrieved.
return
A string holding the package name of the resource.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getResourceName

        String str = mAssets.getResourcePackageName(resid);
        if (str != null) return str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    
public java.lang.StringgetResourceTypeName(int resid)
Return the type name for a given resource identifier.

param
resid The resource identifier whose type name is to be retrieved.
return
A string holding the type name of the resource.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
see
#getResourceName

        String str = mAssets.getResourceTypeName(resid);
        if (str != null) return str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    
public java.lang.StringgetString(int id)
Return the string value associated with a particular resource ID. It will be stripped of any styled text information. {@more}

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
String The string data associated with the resource, stripped of styled text information.

        CharSequence res = getText(id);
        if (res != null) {
            return res.toString();
        }
        throw new NotFoundException("String resource ID #0x"
                                    + Integer.toHexString(id));
    
public java.lang.StringgetString(int id, java.lang.Object formatArgs)
Return the string value associated with a particular resource ID, substituting the format arguments as defined in {@link java.util.Formatter} and {@link java.lang.String#format}. It will be stripped of any styled text information. {@more}

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
formatArgs The format arguments that will be used for substitution.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
String The string data associated with the resource, stripped of styled text information.

        String raw = getString(id);
        return String.format(mConfiguration.locale, raw, formatArgs);
    
public java.lang.String[]getStringArray(int id)
Return the string array associated with a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
The string array associated with the resource.

        String[] res = mAssets.getResourceStringArray(id);
        if (res != null) {
            return res;
        }
        throw new NotFoundException("String array resource ID #0x"
                                    + Integer.toHexString(id));
    
public static android.content.res.ResourcesgetSystem()
Return a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).

        synchronized (mSync) {
            Resources ret = mSystem;
            if (ret == null) {
                ret = new Resources();
                mSystem = ret;
            }

            return ret;
        }
    
public java.lang.CharSequencegetText(int id, java.lang.CharSequence def)
Return the string value associated with a particular resource ID. The returned object will be a String if this is a plain string; it will be some other type of CharSequence if it is styled.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
def The default CharSequence to return.
return
CharSequence The string data associated with the resource, plus possibly styled text information, or def if id is 0 or not found.

        CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
        return res != null ? res : def;
    
public java.lang.CharSequencegetText(int id)
Return the string value associated with a particular resource ID. The returned object will be a String if this is a plain string; it will be some other type of CharSequence if it is styled. {@more}

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
CharSequence The string data associated with the resource, plus possibly styled text information.

        CharSequence res = mAssets.getResourceText(id);
        if (res != null) {
            return res;
        }
        throw new NotFoundException("String resource ID #0x"
                                    + Integer.toHexString(id));
    
public java.lang.CharSequence[]getTextArray(int id)
Return the styled text array associated with a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
The styled text array associated with the resource.

        CharSequence[] res = mAssets.getResourceTextArray(id);
        if (res != null) {
            return res;
        }
        throw new NotFoundException("Text array resource ID #0x"
                                    + Integer.toHexString(id));
    
public voidgetValue(int id, android.util.TypedValue outValue, boolean resolveRefs)
Return the raw data associated with a particular resource ID.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
param
outValue Object in which to place the resource data.
param
resolveRefs If true, a resource that is a reference to another resource will be followed so that you receive the actual final resource data. If false, the TypedValue will be filled in with the reference itself.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        boolean found = mAssets.getResourceValue(id, outValue, resolveRefs);
        if (found) {
            return;
        }
        throw new NotFoundException("Resource ID #0x"
                                    + Integer.toHexString(id));
    
public voidgetValue(java.lang.String name, android.util.TypedValue outValue, boolean resolveRefs)
Return the raw data associated with a particular resource ID. See getIdentifier() for information on how names are mapped to resource IDs, and getString(int) for information on how string resources are retrieved.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

param
name The name of the desired resource. This is passed to getIdentifier() with a default type of "string".
param
outValue Object in which to place the resource data.
param
resolveRefs If true, a resource that is a reference to another resource will be followed so that you receive the actual final resource data. If false, the TypedValue will be filled in with the reference itself.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        int id = getIdentifier(name, "string", null);
        if (id != 0) {
            getValue(id, outValue, resolveRefs);
            return;
        }
        throw new NotFoundException("String resource name " + name);
    
public XmlResourceParsergetXml(int id)
Return an XmlResourceParser through which you can read a generic XML resource for the given resource ID.

The XmlPullParser implementation returned here has some limited functionality. In particular, you can't change its input, and only high-level parsing events are available (since the document was pre-parsed for you at build time, which involved merging text and stripping comments).

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
A new parser object through which you can read the XML data.
see
android.util.AttributeSet

        return loadXmlResourceParser(id, "xml");
    
ColorStateListloadColorStateList(android.util.TypedValue value, int id)

        if (TRACE_FOR_PRELOAD) {
            // Log only framework resources
            if ((id >>> 24) == 0x1) {
                final String name = getResourceName(id);
                if (name != null) android.util.Log.d("PreloadColorStateList", name);
            }
        }

        final int key = (value.assetCookie << 24) | value.data;

        ColorStateList csl;

        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
                value.type <= TypedValue.TYPE_LAST_COLOR_INT) {

            csl = mPreloadedColorStateLists.get(key);
            if (csl != null) {
                return csl;
            }

            csl = ColorStateList.valueOf(value.data);
            if (mPreloading) {
                mPreloadedColorStateLists.put(key, csl);
            }

            return csl;
        }

        csl = getCachedColorStateList(key);
        if (csl != null) {
            return csl;
        }

        csl = mPreloadedColorStateLists.get(key);
        if (csl != null) {
            return csl;
        }

        if (value.string == null) {
            throw new NotFoundException(
                    "Resource is not a ColorStateList (color or path): " + value);
        }
        
        String file = value.string.toString();

        if (file.endsWith(".xml")) {
            try {
                XmlResourceParser rp = loadXmlResourceParser(
                        file, id, value.assetCookie, "colorstatelist"); 
                csl = ColorStateList.createFromXml(this, rp);
                rp.close();
            } catch (Exception e) {
                NotFoundException rnf = new NotFoundException(
                    "File " + file + " from color state list resource ID #0x"
                    + Integer.toHexString(id));
                rnf.initCause(e);
                throw rnf;
            }
        } else {
            throw new NotFoundException(
                    "File " + file + " from drawable resource ID #0x"
                    + Integer.toHexString(id) + ": .xml extension required");
        }

        if (csl != null) {
            if (mPreloading) {
                mPreloadedColorStateLists.put(key, csl);
            } else {
                synchronized (mTmpValue) {
                    //Log.i(TAG, "Saving cached color state list @ #" +
                    //        Integer.toHexString(key.intValue())
                    //        + " in " + this + ": " + csl);
                    mColorStateListCache.put(
                        key, new WeakReference<ColorStateList>(csl));
                }
            }
        }

        return csl;
    
android.graphics.drawable.DrawableloadDrawable(android.util.TypedValue value, int id)


        if (TRACE_FOR_PRELOAD) {
            // Log only framework resources
            if ((id >>> 24) == 0x1) {
                final String name = getResourceName(id);
                if (name != null) android.util.Log.d("PreloadDrawable", name);
            }
        }

        final int key = (value.assetCookie << 24) | value.data;
        Drawable dr = getCachedDrawable(key);

        if (dr != null) {
            return dr;
        }

        Drawable.ConstantState cs = mPreloadedDrawables.get(key);
        if (cs != null) {
            dr = cs.newDrawable();
        } else {
            if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
                    value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
                dr = new ColorDrawable(value.data);
            }

            if (dr == null) {
                if (value.string == null) {
                    throw new NotFoundException(
                            "Resource is not a Drawable (color or path): " + value);
                }

                String file = value.string.toString();

                if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie "
                        + value.assetCookie + ": " + file);

                if (file.endsWith(".xml")) {
                    try {
                        XmlResourceParser rp = loadXmlResourceParser(
                                file, id, value.assetCookie, "drawable");
                        dr = Drawable.createFromXml(this, rp);
                        rp.close();
                    } catch (Exception e) {
                        NotFoundException rnf = new NotFoundException(
                            "File " + file + " from drawable resource ID #0x"
                            + Integer.toHexString(id));
                        rnf.initCause(e);
                        throw rnf;
                    }

                } else {
                    try {
                        InputStream is = mAssets.openNonAsset(
                                value.assetCookie, file, AssetManager.ACCESS_BUFFER);
        //                System.out.println("Opened file " + file + ": " + is);
                        dr = Drawable.createFromResourceStream(this, value, is, file);
                        is.close();
        //                System.out.println("Created stream: " + dr);
                    } catch (Exception e) {
                        NotFoundException rnf = new NotFoundException(
                            "File " + file + " from drawable resource ID #0x"
                            + Integer.toHexString(id));
                        rnf.initCause(e);
                        throw rnf;
                    }
                }
            }
        }

        if (dr != null) {
            dr.setChangingConfigurations(value.changingConfigurations);
            cs = dr.getConstantState();
            if (cs != null) {
                if (mPreloading) {
                    mPreloadedDrawables.put(key, cs);
                } else {
                    synchronized (mTmpValue) {
                        //Log.i(TAG, "Saving cached drawable @ #" +
                        //        Integer.toHexString(key.intValue())
                        //        + " in " + this + ": " + cs);
                        mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs));
                    }
                }
            }
        }

        return dr;
    
XmlResourceParserloadXmlResourceParser(int id, java.lang.String type)

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);
            if (value.type == TypedValue.TYPE_STRING) {
                return loadXmlResourceParser(value.string.toString(), id,
                        value.assetCookie, type);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    
XmlResourceParserloadXmlResourceParser(java.lang.String file, int id, int assetCookie, java.lang.String type)

        if (id != 0) {
            try {
                // These may be compiled...
                synchronized (mCachedXmlBlockIds) {
                    // First see if this block is in our cache.
                    final int num = mCachedXmlBlockIds.length;
                    for (int i=0; i<num; i++) {
                        if (mCachedXmlBlockIds[i] == id) {
                            //System.out.println("**** REUSING XML BLOCK!  id="
                            //                   + id + ", index=" + i);
                            return mCachedXmlBlocks[i].newParser();
                        }
                    }

                    // Not in the cache, create a new block and put it at
                    // the next slot in the cache.
                    XmlBlock block = mAssets.openXmlBlockAsset(
                            assetCookie, file);
                    if (block != null) {
                        int pos = mLastCachedXmlBlockIndex+1;
                        if (pos >= num) pos = 0;
                        mLastCachedXmlBlockIndex = pos;
                        XmlBlock oldBlock = mCachedXmlBlocks[pos];
                        if (oldBlock != null) {
                            oldBlock.close();
                        }
                        mCachedXmlBlockIds[pos] = id;
                        mCachedXmlBlocks[pos] = block;
                        //System.out.println("**** CACHING NEW XML BLOCK!  id="
                        //                   + id + ", index=" + pos);
                        return block.newParser();
                    }
                }
            } catch (Exception e) {
                NotFoundException rnf = new NotFoundException(
                        "File " + file + " from xml type " + type + " resource ID #0x"
                        + Integer.toHexString(id));
                rnf.initCause(e);
                throw rnf;
            }
        }

        throw new NotFoundException(
                "File " + file + " from xml type " + type + " resource ID #0x"
                + Integer.toHexString(id));
    
public final android.content.res.Resources$ThemenewTheme()
Generate a new Theme object for this set of Resources. It initially starts out empty.

return
Theme The newly created Theme container.

        return new Theme();
    
public TypedArrayobtainAttributes(android.util.AttributeSet set, int[] attrs)
Retrieve a set of basic attribute values from an AttributeSet, not performing styling of them using a theme and/or style resources.

param
set The current attribute values to retrieve.
param
attrs The specific attributes to be retrieved.
return
Returns a TypedArray holding an array of the attribute values. Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when done with it.
see
Theme#obtainStyledAttributes(AttributeSet, int[], int, int)

        int len = attrs.length;
        TypedArray array = getCachedStyledAttributes(len);

        // XXX note that for now we only work with compiled XML files.
        // To support generic XML files we will need to manually parse
        // out the attributes from the XML file (applying type information
        // contained in the resources and such).
        XmlBlock.Parser parser = (XmlBlock.Parser)set;
        mAssets.retrieveAttributes(parser.mParseState, attrs,
                array.mData, array.mIndices);

        array.mRsrcs = attrs;
        array.mXml = parser;

        return array;
    
public TypedArrayobtainTypedArray(int id)
Return an array of heterogeneous values.

param
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.
return
Returns a TypedArray holding an array of the array values. Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when done with it.

        int len = mAssets.getArraySize(id);
        if (len < 0) {
            throw new NotFoundException("Array resource ID #0x"
                                        + Integer.toHexString(id));
        }
        
        TypedArray array = getCachedStyledAttributes(len);
        array.mLength = mAssets.retrieveArray(id, array.mData);
        array.mIndices[0] = 0;
        
        return array;
    
public java.io.InputStreamopenRawResource(int id)
Open a data stream for reading a raw resource. This can only be used with resources whose value is the name of an asset files -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color resources.

param
id The resource identifier to open, as generated by the appt tool.
return
InputStream Access to the resource data.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        synchronized (mTmpValue) {
            return openRawResource(id, mTmpValue);
        }
    
public java.io.InputStreamopenRawResource(int id, android.util.TypedValue value)
Open a data stream for reading a raw resource. This can only be used with resources whose value is the name of an asset file -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color resources.

param
id The resource identifier to open, as generated by the appt tool.
param
value The TypedValue object to hold the resource information.
return
InputStream Access to the resource data.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        getValue(id, value, true);

        try {
            return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
                    AssetManager.ACCESS_STREAMING);
        } catch (Exception e) {
            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
                    " from drawable resource ID #0x" + Integer.toHexString(id));
            rnf.initCause(e);
            throw rnf;
        }
    
public AssetFileDescriptoropenRawResourceFd(int id)
Open a file descriptor for reading a raw resource. This can only be used with resources whose value is the name of an asset files -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color resources.

This function only works for resources that are stored in the package as uncompressed data, which typically includes things like mp3 files and png images.

param
id The resource identifier to open, as generated by the appt tool.
return
AssetFileDescriptor A new file descriptor you can use to read the resource. This includes the file descriptor itself, as well as the offset and length of data where the resource appears in the file. A null is returned if the file exists but is compressed.
throws
NotFoundException Throws NotFoundException if the given ID does not exist.

        synchronized (mTmpValue) {
            TypedValue value = mTmpValue;
            getValue(id, value, true);

            try {
                return mAssets.openNonAssetFd(
                    value.assetCookie, value.string.toString());
            } catch (Exception e) {
                NotFoundException rnf = new NotFoundException(
                    "File " + value.string.toString()
                    + " from drawable resource ID #0x"
                    + Integer.toHexString(id));
                rnf.initCause(e);
                throw rnf;
            }

        }
    
public voidparseBundleExtra(java.lang.String tagName, android.util.AttributeSet attrs, android.os.Bundle outBundle)
Parse a name/value pair out of an XML tag holding that data. The AttributeSet must be holding the data defined by {@link android.R.styleable#Extra}. The following value types are supported:
  • {@link TypedValue#TYPE_STRING}: {@link Bundle#putCharSequence Bundle.putCharSequence()}
  • {@link TypedValue#TYPE_INT_BOOLEAN}: {@link Bundle#putCharSequence Bundle.putBoolean()}
  • {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}: {@link Bundle#putCharSequence Bundle.putBoolean()}
  • {@link TypedValue#TYPE_FLOAT}: {@link Bundle#putCharSequence Bundle.putFloat()}

param
tagName The name of the tag these attributes come from; this is only used for reporting error messages.
param
attrs The attributes from which to retrieve the name/value pair.
param
outBundle The Bundle in which to place the parsed value.
throws
XmlPullParserException If the attributes are not valid.

        TypedArray sa = obtainAttributes(attrs,
                com.android.internal.R.styleable.Extra);

        String name = sa.getString(
                com.android.internal.R.styleable.Extra_name);
        if (name == null) {
            sa.recycle();
            throw new XmlPullParserException("<" + tagName
                    + "> requires an android:name attribute at "
                    + attrs.getPositionDescription());
        }

        TypedValue v = sa.peekValue(
                com.android.internal.R.styleable.Extra_value);
        if (v != null) {
            if (v.type == TypedValue.TYPE_STRING) {
                CharSequence cs = v.coerceToString();
                outBundle.putCharSequence(name, cs);
            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
                outBundle.putBoolean(name, v.data != 0);
            } else if (v.type >= TypedValue.TYPE_FIRST_INT
                    && v.type <= TypedValue.TYPE_LAST_INT) {
                outBundle.putInt(name, v.data);
            } else if (v.type == TypedValue.TYPE_FLOAT) {
                outBundle.putFloat(name, v.getFloat());
            } else {
                sa.recycle();
                throw new XmlPullParserException("<" + tagName
                        + "> only supports string, integer, float, color, and boolean at "
                        + attrs.getPositionDescription());
            }
        } else {
            sa.recycle();
            throw new XmlPullParserException("<" + tagName
                    + "> requires an android:value or android:resource attribute at "
                    + attrs.getPositionDescription());
        }

        sa.recycle();
    
public voidparseBundleExtras(XmlResourceParser parser, android.os.Bundle outBundle)
Parse a series of {@link android.R.styleable#Extra <extra>} tags from an XML file. You call this when you are at the parent tag of the extra tags, and it return once all of the child tags have been parsed. This will call {@link #parseBundleExtra} for each extra tag encountered.

param
parser The parser from which to retrieve the extras.
param
outBundle A Bundle in which to place all parsed extras.
throws
XmlPullParserException
throws
IOException

        int outerDepth = parser.getDepth();
        int type;
        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            
            String nodeName = parser.getName();
            if (nodeName.equals("extra")) {
                parseBundleExtra("extra", parser, outBundle);
                XmlUtils.skipCurrentTag(parser);

            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }        
    
public final voidstartPreloading()
Start preloading of resource data using this Resources object. Only for use by the zygote process for loading common system resources. {@hide}

        synchronized (mSync) {
            if (mPreloaded) {
                throw new IllegalStateException("Resources already preloaded");
            }
            mPreloaded = true;
            mPreloading = true;
        }
    
public voidupdateConfiguration(Configuration config, android.util.DisplayMetrics metrics)
Store the newly updated configuration.

        synchronized (mTmpValue) {
            int configChanges = 0xfffffff;
            if (config != null) {
                configChanges = mConfiguration.updateFrom(config);
            }
            if (metrics != null) {
                mMetrics.setTo(metrics);
            }
            mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
            String locale = null;
            if (mConfiguration.locale != null) {
                locale = mConfiguration.locale.getLanguage();
                if (mConfiguration.locale.getCountry() != null) {
                    locale += "-" + mConfiguration.locale.getCountry();
                }
            }
            int width, height;
            if (mMetrics.widthPixels >= mMetrics.heightPixels) {
                width = mMetrics.widthPixels;
                height = mMetrics.heightPixels;
            } else {
                //noinspection SuspiciousNameCombination
                width = mMetrics.heightPixels;
                //noinspection SuspiciousNameCombination
                height = mMetrics.widthPixels;
            }
            int keyboardHidden = mConfiguration.keyboardHidden;
            if (keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO
                    && mConfiguration.hardKeyboardHidden
                            == Configuration.HARDKEYBOARDHIDDEN_YES) {
                keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
            }
            mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
                    locale, mConfiguration.orientation,
                    mConfiguration.touchscreen,
                    (int)(mMetrics.density*160), mConfiguration.keyboard,
                    keyboardHidden, mConfiguration.navigation, width, height,
                    sSdkVersion);
            int N = mDrawableCache.size();
            if (DEBUG_CONFIG) {
                Log.d(TAG, "Cleaning up drawables config changes: 0x"
                        + Integer.toHexString(configChanges));
            }
            for (int i=0; i<N; i++) {
                WeakReference<Drawable.ConstantState> ref = mDrawableCache.valueAt(i);
                if (ref != null) {
                    Drawable.ConstantState cs = ref.get();
                    if (cs != null) {
                        if (Configuration.needNewResources(
                                configChanges, cs.getChangingConfigurations())) {
                            if (DEBUG_CONFIG) {
                                Log.d(TAG, "FLUSHING #0x"
                                        + Integer.toHexString(mDrawableCache.keyAt(i))
                                        + " / " + cs + " with changes: 0x"
                                        + Integer.toHexString(cs.getChangingConfigurations()));
                            }
                            mDrawableCache.setValueAt(i, null);
                        } else if (DEBUG_CONFIG) {
                            Log.d(TAG, "(Keeping #0x"
                                    + Integer.toHexString(mDrawableCache.keyAt(i))
                                    + " / " + cs + " with changes: 0x"
                                    + Integer.toHexString(cs.getChangingConfigurations())
                                    + ")");
                        }
                    }
                }
            }
            mDrawableCache.clear();
            mColorStateListCache.clear();
            flushLayoutCache();
        }
        synchronized (mSync) {
            if (mPluralRule != null) {
                mPluralRule = PluralRules.ruleForLocale(config.locale);
            }
        }
    
public static voidupdateSystemConfiguration(Configuration config, android.util.DisplayMetrics metrics)
Update the system resources configuration if they have previously been initialized.

hide

        if (mSystem != null) {
            mSystem.updateConfiguration(config, metrics);
            //Log.i(TAG, "Updated system resources " + mSystem
            //        + ": " + mSystem.getConfiguration());
        }