Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2006 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package android.content.res;
  
  
  
  
  import android.os.Build;
  import android.os.Bundle;
  import android.util.Log;
  
  import java.util.Locale;

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.
  
  public class Resources {
      static final String TAG = "Resources";
      private static final boolean DEBUG_LOAD = false;
      private static final boolean DEBUG_CONFIG = false;
      private static final boolean TRACE_FOR_PRELOAD = false;
  
      // Use the current SDK version code.  If we are a development build,
      // also allow the previous SDK version + 1.
      private static final int sSdkVersion = ..
              + ("REL".equals(..) ? 0 : 1);
      private static final Object mSync = new Object();
      private static Resources mSystem = null;
      
      // Information about preloaded resources.  Note that they are not
      // protected by a lock, because while preloading in zygote we are all
      // single-threaded, and after that these are immutable.
      private static final LongSparseArray<Drawable.ConstantStatesPreloadedDrawables
              = new LongSparseArray<Drawable.ConstantState>();
      private static final SparseArray<ColorStateListmPreloadedColorStateLists
              = new SparseArray<ColorStateList>();
      private static boolean mPreloaded;
  
      /*package*/ final TypedValue mTmpValue = new TypedValue();
  
      // These are protected by the mTmpValue lock.
              = new LongSparseArray<WeakReference<Drawable.ConstantState> >();
              = new SparseArray<WeakReference<ColorStateList> >();
      private boolean mPreloading;
  
      /*package*/ TypedArray mCachedStyledAttributes = null;
  
      private int mLastCachedXmlBlockIndex = -1;
      private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 };
      private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4];
  
      /*package*/ final AssetManager mAssets;
      private final Configuration mConfiguration = new Configuration();
      /*package*/ final DisplayMetrics mMetrics = new DisplayMetrics();
      
      private Display mDefaultDisplay;
  
      private static final LongSparseArray<ObjectEMPTY_ARRAY = new LongSparseArray<Object>() {
          @Override
          public void put(long kObject o) {
              throw new UnsupportedOperationException();
          }
          @Override
         public void append(long kObject o) {
             throw new UnsupportedOperationException();
         }
     };
 
     @SuppressWarnings("unchecked")
     private static <T> LongSparseArray<T> emptySparseArray() {
         return (LongSparseArray<T>) ;
     }

    
This exception is thrown by the resource APIs when a requested resource can not be found.
 
     public static class NotFoundException extends RuntimeException {
         public NotFoundException() {
         }
 
         public NotFoundException(String name) {
             super(name);
         }
     }

    
Create a new Resources object on top of an existing set of assets in an AssetManager.

Parameters:
assets Previously created AssetManager.
metrics Current display metrics to consider when selecting/computing resource values.
config Desired device configuration to consider when selecting/computing resource values (optional).
 
     public Resources(AssetManager assetsDisplayMetrics metrics,
             Configuration config) {
         this(assetsmetricsconfig, (CompatibilityInfonull);
     }

    
Creates a new Resources object with CompatibilityInfo.

Parameters:
assets Previously created AssetManager.
metrics Current display metrics to consider when selecting/computing resource values.
config Desired device configuration to consider when selecting/computing resource values (optional).
compInfo this resource's compatibility info. It will use the default compatibility info when it's null.
Hide:
 
     public Resources(AssetManager assetsDisplayMetrics metrics,
             Configuration configCompatibilityInfo compInfo) {
          = assets;
         .setToDefaults();
         if (compInfo == null) {
         } else {
              = compInfo;
         }
         updateConfiguration(configmetrics);
         assets.ensureStringBlocks();
     }

    
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).
 
     public static Resources getSystem() {
         synchronized () {
             Resources ret = ;
             if (ret == null) {
                 ret = new Resources();
                  = ret;
             }
 
             return ret;
         }
     }

    
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.

Parameters:
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.
Returns:
CharSequence The string data associated with the resource, plus possibly styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public CharSequence getText(int idthrows NotFoundException {
         CharSequence res = .getResourceText(id);
         if (res != null) {
             return res;
         }
         throw new NotFoundException("String resource ID #0x"
                                     + Integer.toHexString(id));
     }

    

Parameters:
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.
Returns:
CharSequence The string data associated with the resource, plus possibly styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public CharSequence getQuantityText(int idint quantitythrows NotFoundException {
         PluralRules rule = getPluralRule();
         CharSequence res = .getResourceBagText(idrule.attrForNumber(quantity));
         if (res != null) {
             return res;
         }
         res = .getResourceBagText(id.);
         if (res != null) {
             return res;
         }
         throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
                 + " quantity=" + quantity
                 + " item=" + PluralRules.stringForQuantity(rule.quantityForNumber(quantity)));
     }
 
     private PluralRules getPluralRule() {
         synchronized () {
             if ( == null) {
                  = PluralRules.ruleForLocale(.);
             }
             return ;
         }
     }

    
Return the string value associated with a particular resource ID. It will be stripped of any styled text information.

Parameters:
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.
Returns:
String The string data associated with the resource, stripped of styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public String getString(int idthrows NotFoundException {
         CharSequence res = getText(id);
         if (res != null) {
             return res.toString();
         }
         throw new NotFoundException("String resource ID #0x"
                                     + Integer.toHexString(id));
     }


    
Return the string value associated with a particular resource ID, substituting the format arguments as defined in java.util.Formatter and java.lang.String.format(java.lang.String,java.lang.Object[]). It will be stripped of any styled text information.

Parameters:
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.
formatArgs The format arguments that will be used for substitution.
Returns:
String The string data associated with the resource, stripped of styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public String getString(int idObject... formatArgsthrows NotFoundException {
         String raw = getString(id);
         return String.format(.rawformatArgs);
     }

    
Return the string value associated with a particular resource ID for a particular numerical quantity, substituting the format arguments as defined in java.util.Formatter and java.lang.String.format(java.lang.String,java.lang.Object[]). It will be stripped of any styled text information.

Parameters:
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.
quantity The number used to get the correct string for the current language's plural rules.
formatArgs The format arguments that will be used for substitution.
Returns:
String The string data associated with the resource, stripped of styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public String getQuantityString(int idint quantityObject... formatArgs)
             throws NotFoundException {
         String raw = getQuantityText(idquantity).toString();
         return String.format(.rawformatArgs);
     }

    
Return the string value associated with a particular resource ID for a particular numerical quantity.

Parameters:
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.
quantity The number used to get the correct string for the current language's plural rules.
Returns:
String The string data associated with the resource, stripped of styled text information.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public String getQuantityString(int idint quantitythrows NotFoundException {
         return getQuantityText(idquantity).toString();
     }

    
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.

Parameters:
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.
def The default CharSequence to return.
Returns:
CharSequence The string data associated with the resource, plus possibly styled text information, or def if id is 0 or not found.
 
     public CharSequence getText(int idCharSequence def) {
         CharSequence res = id != 0 ? .getResourceText(id) : null;
         return res != null ? res : def;
     }

    
Return the styled text array associated with a particular resource ID.

Parameters:
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.
Returns:
The styled text array associated with the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public CharSequence[] getTextArray(int idthrows NotFoundException {
         CharSequence[] res = .getResourceTextArray(id);
         if (res != null) {
             return res;
         }
         throw new NotFoundException("Text array resource ID #0x"
                                     + Integer.toHexString(id));
     }

    
Return the string array associated with a particular resource ID.

Parameters:
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.
Returns:
The string array associated with the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public String[] getStringArray(int idthrows NotFoundException {
         String[] res = .getResourceStringArray(id);
         if (res != null) {
             return res;
         }
         throw new NotFoundException("String array resource ID #0x"
                                     + Integer.toHexString(id));
     }

    
Return the int array associated with a particular resource ID.

Parameters:
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.
Returns:
The int array associated with the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public int[] getIntArray(int idthrows NotFoundException {
         int[] res = .getArrayIntResource(id);
         if (res != null) {
             return res;
         }
         throw new NotFoundException("Int array resource ID #0x"
                                     + Integer.toHexString(id));
     }

    
Return an array of heterogeneous values.

Parameters:
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.
Returns:
Returns a TypedArray holding an array of the array values. Be sure to call TypedArray.recycle() when done with it.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public TypedArray obtainTypedArray(int idthrows NotFoundException {
         int len = .getArraySize(id);
         if (len < 0) {
             throw new NotFoundException("Array resource ID #0x"
                                         + Integer.toHexString(id));
         }
         
         TypedArray array = getCachedStyledAttributes(len);
         array.mLength = .retrieveArray(idarray.mData);
         array.mIndices[0] = 0;
         
         return array;
     }

    
Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current android.util.DisplayMetrics associated with the resources.

Parameters:
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.
Returns:
Resource dimension value multiplied by the appropriate metric.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getDimensionPixelOffset(int)
getDimensionPixelSize(int)
 
     public float getDimension(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type == .) {
                 return TypedValue.complexToDimension(value.data);
             }
             throw new NotFoundException(
                     "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                     + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
Retrieve a dimensional for a particular resource ID for use as an offset in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for you. An offset conversion involves simply truncating the base value to an integer.

Parameters:
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.
Returns:
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getDimension(int)
getDimensionPixelSize(int)
 
     public int getDimensionPixelOffset(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type == .) {
                 return TypedValue.complexToDimensionPixelOffset(
                         value.data);
             }
             throw new NotFoundException(
                     "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                     + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), 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.

Parameters:
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.
Returns:
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getDimension(int)
getDimensionPixelOffset(int)
 
     public int getDimensionPixelSize(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type == .) {
                 return TypedValue.complexToDimensionPixelSize(
                         value.data);
             }
             throw new NotFoundException(
                     "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                     + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
Retrieve a fractional unit for a particular resource ID.

Parameters:
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.
base The base value of this fraction. In other words, a standard fraction is multiplied by this value.
pbase The parent base value of this fraction. In other words, a parent fraction (nn%p) is multiplied by this value.
Returns:
Attribute fractional value multiplied by the appropriate base value.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public float getFraction(int idint baseint pbase) {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type == .) {
                 return TypedValue.complexToFraction(value.databasepbase);
             }
             throw new NotFoundException(
                     "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                     + Integer.toHexString(value.type) + " is not valid");
         }
     }
    
    
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.

Parameters:
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.
Returns:
Drawable An object that can be used to draw this resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public Drawable getDrawable(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             return loadDrawable(valueid);
         }
     }

    
Return a movie object associated with the particular resource ID.

Parameters:
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:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public Movie getMovie(int idthrows NotFoundException {
         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;
     }

    
Return a color integer associated with a particular resource ID. If the resource holds a complex ColorStateList, then the default color from the set is returned.

Parameters:
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.
Returns:
Returns a single color value in the form 0xAARRGGBB.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public int getColor(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type >= .
                 && value.type <= .) {
                 return value.data;
             } else if (value.type == .) {
                 ColorStateList csl = loadColorStateList(id);
                 return csl.getDefaultColor();
             }
             throw new NotFoundException(
                 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                 + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
Return a color state list associated with a particular resource ID. The resource may contain either a single raw color value, or a complex ColorStateList holding multiple possible colors.

Parameters:
id The desired resource identifier of a ColorStateList, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
Returns:
Returns a ColorStateList object containing either a single solid color or multiple colors that can be selected based on a state.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public ColorStateList getColorStateList(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             return loadColorStateList(valueid);
         }
     }

    
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.

Parameters:
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.
Returns:
Returns the boolean value contained in the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public boolean getBoolean(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type >= .
                 && value.type <= .) {
                 return value.data != 0;
             }
             throw new NotFoundException(
                 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                 + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
Return an integer associated with a particular resource ID.

Parameters:
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.
Returns:
Returns the integer value contained in the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public int getInteger(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
             if (value.type >= .
                 && value.type <= .) {
                 return value.data;
             }
             throw new NotFoundException(
                 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                 + Integer.toHexString(value.type) + " is not valid");
         }
     }

    
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 getXml(int) with a layout resource.

Parameters:
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.
Returns:
A new parser object through which you can read the XML data.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getXml(int)
 
     public XmlResourceParser getLayout(int idthrows NotFoundException {
         return loadXmlResourceParser(id"layout");
     }

    
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 getXml(int) with an animation resource.

Parameters:
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.
Returns:
A new parser object through which you can read the XML data.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getXml(int)
 
     public XmlResourceParser getAnimation(int idthrows NotFoundException {
         return loadXmlResourceParser(id"anim");
     }

    
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).

Parameters:
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.
Returns:
A new parser object through which you can read the XML data.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
android.util.AttributeSet
 
     public XmlResourceParser getXml(int idthrows NotFoundException {
         return loadXmlResourceParser(id"xml");
     }

    
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.

Parameters:
id The resource identifier to open, as generated by the appt tool.
Returns:
InputStream Access to the resource data.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public InputStream openRawResource(int idthrows NotFoundException {
         synchronized () {
             return openRawResource(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 file -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color resources.

Parameters:
id The resource identifier to open, as generated by the appt tool.
value The TypedValue object to hold the resource information.
Returns:
InputStream Access to the resource data.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public InputStream openRawResource(int idTypedValue valuethrows NotFoundException {
         getValue(idvaluetrue);
 
         try {
             return .openNonAsset(value.assetCookievalue.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;
         }
     }

    
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.

Parameters:
id The resource identifier to open, as generated by the appt tool.
Returns:
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:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public AssetFileDescriptor openRawResourceFd(int idthrows NotFoundException {
         synchronized () {
             TypedValue value = ;
             getValue(idvaluetrue);
 
             try {
                 return .openNonAssetFd(
                     value.assetCookievalue.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;
             }
 
         }
     }

    
Return the raw data associated with a particular resource ID.

Parameters:
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.
outValue Object in which to place the resource data.
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:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public void getValue(int idTypedValue outValueboolean resolveRefs)
             throws NotFoundException {
         boolean found = .getResourceValue(idoutValueresolveRefs);
         if (found) {
             return;
         }
         throw new NotFoundException("Resource ID #0x"
                                     + Integer.toHexString(id));
     }

    
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.

Parameters:
name The name of the desired resource. This is passed to getIdentifier() with a default type of "string".
outValue Object in which to place the resource data.
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:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
 
     public void getValue(String nameTypedValue outValueboolean resolveRefs)
             throws NotFoundException {
         int id = getIdentifier(name"string"null);
         if (id != 0) {
             getValue(idoutValueresolveRefs);
             return;
         }
         throw new NotFoundException("String resource name " + name);
     }

    
This class holds the current attribute values for a particular theme. In other words, a Theme is a set of values for resource attributes; these are used in conjunction with TypedArray to resolve the final value for an attribute.

The Theme's attributes come into play in two ways: (1) a styled attribute can explicit reference a value in the theme through the "?themeAttribute" syntax; (2) if no value has been defined for a particular styled attribute, as a last resort we will try to find that attribute's value in the Theme.

You will normally use the obtainStyledAttributes(int[]) APIs to retrieve XML attributes with style and theme information applied.

 
     public final class Theme {
        
Place new attribute values into the theme. The style resource specified by resid will be retrieved from this Theme's resources, its values placed into the Theme object.

The semantics of this function depends on the force argument: If false, only values that are not already defined in the theme will be copied from the system resource; otherwise, if any of the style's attributes are already defined in the theme, the current values in the theme will be overwritten.

Parameters:
resid The resource ID of a style resource from which to obtain attribute values.
force If true, values in the style resource will always be used in the theme; otherwise, they will only be used if not already defined in the theme.
 
         public void applyStyle(int residboolean force) {
             AssetManager.applyThemeStyle(residforce);
         }

        
Set this theme to hold the same contents as the theme other. If both of these themes are from the same Resources object, they will be identical after this function returns. If they are from different Resources, only the resources they have in common will be set in this theme.

Parameters:
other The existing Theme to copy from.
 
         public void setTo(Theme other) {
             AssetManager.copyTheme(other.mTheme);
         }

        
Return a StyledAttributes holding the values defined by Theme which are listed in attrs.

Be sure to call StyledAttributes.recycle() when you are done with the array.

Parameters:
attrs The desired attributes.
Returns:
Returns a TypedArray holding an array of the attribute values. Be sure to call TypedArray.recycle() when done with it.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
Resources.obtainAttributes(android.util.AttributeSet,int[])
obtainStyledAttributes(int,int[])
obtainStyledAttributes(android.util.AttributeSet,int[],int,int)
 
         public TypedArray obtainStyledAttributes(int[] attrs) {
             int len = attrs.length;
             TypedArray array = getCachedStyledAttributes(len);
             array.mRsrcs = attrs;
             AssetManager.applyStyle(, 0, 0, 0, attrs,
                    array.mDataarray.mIndices);
            return array;
        }

        
Return a StyledAttributes holding the values defined by the style resource resid which are listed in attrs.

Be sure to call StyledAttributes.recycle() when you are done with the array.

Parameters:
resid The desired style resource.
attrs The desired attributes in the style.
Returns:
Returns a TypedArray holding an array of the attribute values. Be sure to call TypedArray.recycle() when done with it.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
Resources.obtainAttributes(android.util.AttributeSet,int[])
obtainStyledAttributes(int[])
obtainStyledAttributes(android.util.AttributeSet,int[],int,int)
        public TypedArray obtainStyledAttributes(int residint[] attrs)
                throws NotFoundException {
            int len = attrs.length;
            TypedArray array = getCachedStyledAttributes(len);
            array.mRsrcs = attrs;
            AssetManager.applyStyle(, 0, resid, 0, attrs,
                    array.mDataarray.mIndices);
            if (false) {
                int[] data = array.mData;
                
                ..println("**********************************************************");
                ..println("**********************************************************");
                ..println("**********************************************************");
                ..println("Attributes:");
                String s = "  Attrs:";
                int i;
                for (i=0; i<attrs.lengthi++) {
                    s = s + " 0x" + Integer.toHexString(attrs[i]);
                }
                ..println(s);
                s = "  Found:";
                TypedValue value = new TypedValue();
                for (i=0; i<attrs.lengthi++) {
                    int d = i*.;
                    value.type = data[d+.];
                    value.data = data[d+.];
                    value.assetCookie = data[d+.];
                    value.resourceId = data[d+.];
                    s = s + " 0x" + Integer.toHexString(attrs[i])
                        + "=" + value;
                }
                ..println(s);
            }
            return array;
        }

        
Return a StyledAttributes holding the attribute values in set that are listed in attrs. In addition, if the given AttributeSet specifies a style class (through the "style" attribute), that style will be applied on top of the base attributes it defines.

Be sure to call StyledAttributes.recycle() when you are done with the array.

When determining the final value of a particular attribute, there are four inputs that come into play:

  1. Any attribute values in the given AttributeSet.
  2. The style resource specified in the AttributeSet (named "style").
  3. The default style specified by defStyleAttr and defStyleRes
  4. The base values in this theme.

Each of these inputs is considered in-order, with the first listed taking precedence over the following ones. In other words, if in the AttributeSet you have supplied <Button textColor="#ff000000">, then the button's text will always be black, regardless of what is specified in any of the styles.

Parameters:
set The base set of attribute values. May be null.
attrs The desired attributes to be retrieved.
defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies defaults values for the StyledAttributes. Can be 0 to not look for defaults.
defStyleRes A resource identifier of a style resource that supplies default values for the StyledAttributes, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.
Returns:
Returns a TypedArray holding an array of the attribute values. Be sure to call TypedArray.recycle() when done with it.
See also:
Resources.obtainAttributes(android.util.AttributeSet,int[])
obtainStyledAttributes(int[])
obtainStyledAttributes(int,int[])
        public TypedArray obtainStyledAttributes(AttributeSet set,
                int[] attrsint defStyleAttrint defStyleRes) {
            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;
            AssetManager.applyStyle(
                defStyleAttrdefStyleRes,
                parser != null ? parser.mParseState : 0, attrs,
                        array.mDataarray.mIndices);
            array.mRsrcs = attrs;
            array.mXml = parser;
            if (false) {
                int[] data = array.mData;
                
                ..println("Attributes:");
                String s = "  Attrs:";
                int i;
                for (i=0; i<set.getAttributeCount(); i++) {
                    s = s + " " + set.getAttributeName(i);
                    int id = set.getAttributeNameResource(i);
                    if (id != 0) {
                        s = s + "(0x" + Integer.toHexString(id) + ")";
                    }
                    s = s + "=" + set.getAttributeValue(i);
                }
                ..println(s);
                s = "  Found:";
                TypedValue value = new TypedValue();
                for (i=0; i<attrs.lengthi++) {
                    int d = i*.;
                    value.type = data[d+.];
                    value.data = data[d+.];
                    value.assetCookie = data[d+.];
                    value.resourceId = data[d+.];
                    s = s + " 0x" + Integer.toHexString(attrs[i])
                        + "=" + value;
                }
                ..println(s);
            }
            return array;
        }

        
Retrieve the value of an attribute in the Theme. The contents of outValue are ultimately filled in by Resources.getValue(int,android.util.TypedValue,boolean).

Parameters:
resid The resource identifier of the desired theme attribute.
outValue Filled in with the ultimate resource value supplied by the attribute.
resolveRefs If true, resource references will be walked; if false, outValue may be a TYPE_REFERENCE. In either case, it will never be a TYPE_ATTRIBUTE.
Returns:
boolean Returns true if the attribute was found and outValue is valid, else false.
        public boolean resolveAttribute(int residTypedValue outValue,
                boolean resolveRefs) {
            boolean got = .getThemeValue(residoutValueresolveRefs);
            if (false) {
                ..println(
                    "resolveAttribute #" + Integer.toHexString(resid)
                    + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type)
                    + ", data=0x" + Integer.toHexString(outValue.data));
            }
            return got;
        }

        
Print contents of this theme out to the log. For debugging only.

Parameters:
priority The log priority to use.
tag The log tag to use.
prefix Text to prefix each line printed.
        public void dump(int priorityString tagString prefix) {
            AssetManager.dumpTheme(prioritytagprefix);
        }
        
        protected void finalize() throws Throwable {
            super.finalize();
            .releaseTheme();
        }
        /*package*/ Theme() {
             = Resources.this.;
             = .createTheme();
        }
        private final AssetManager mAssets;
        private final int mTheme;
    }

    
Generate a new Theme object for this set of Resources. It initially starts out empty.

Returns:
Theme The newly created Theme container.
    public final Theme newTheme() {
        return new Theme();
    }

    
Retrieve a set of basic attribute values from an AttributeSet, not performing styling of them using a theme and/or style resources.

Parameters:
set The current attribute values to retrieve.
attrs The specific attributes to be retrieved.
Returns:
Returns a TypedArray holding an array of the attribute values. Be sure to call TypedArray.recycle() when done with it.
See also:
Resources.Theme.obtainStyledAttributes(android.util.AttributeSet,int[],int,int)
    public TypedArray obtainAttributes(AttributeSet setint[] attrs) {
        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;
        .retrieveAttributes(parser.mParseStateattrs,
                array.mDataarray.mIndices);
        array.mRsrcs = attrs;
        array.mXml = parser;
        return array;
    }

    
Store the newly updated configuration.
    public void updateConfiguration(Configuration config,
            DisplayMetrics metrics) {
        synchronized () {
            int configChanges = 0xfffffff;
            if (config != null) {
                configChanges = .updateFrom(config);
            }
            if (. == null) {
                . = Locale.getDefault();
            }
            if (metrics != null) {
                .setTo(metrics);
                .updateMetrics(,
                        ..);
            }
            String locale = null;
            if (. != null) {
                locale = ..getLanguage();
                if (..getCountry() != null) {
                    locale += "-" + ..getCountry();
                }
            }
            int widthheight;
            if (. >= .) {
                width = .;
                height = .;
            } else {
                //noinspection SuspiciousNameCombination
                width = .;
                //noinspection SuspiciousNameCombination
                height = .;
            }
            int keyboardHidden = .;
            if (keyboardHidden == .
                    && .
                            == .) {
                keyboardHidden = .;
            }
                    locale.,
                    .,
                    (int)(.*160), .,
                    keyboardHidden.widthheight,
                    ..);
            int N = .size();
            if () {
                Log.d("Cleaning up drawables config changes: 0x"
                        + Integer.toHexString(configChanges));
            }
            for (int i=0; i<Ni++) {
                WeakReference<Drawable.ConstantStateref = .valueAt(i);
                if (ref != null) {
                    Drawable.ConstantState cs = ref.get();
                    if (cs != null) {
                        if (Configuration.needNewResources(
                                configChangescs.getChangingConfigurations())) {
                            if () {
                                Log.d("FLUSHING #0x"
                                        + Long.toHexString(.keyAt(i))
                                        + " / " + cs + " with changes: 0x"
                                        + Integer.toHexString(cs.getChangingConfigurations()));
                            }
                            .setValueAt(inull);
                        } else if () {
                            Log.d("(Keeping #0x"
                                    + Long.toHexString(.keyAt(i))
                                    + " / " + cs + " with changes: 0x"
                                    + Integer.toHexString(cs.getChangingConfigurations())
                                    + ")");
                        }
                    }
                }
            }
            .clear();
            .clear();
            flushLayoutCache();
        }
        synchronized () {
            if ( != null) {
                 = PluralRules.ruleForLocale(config.locale);
            }
        }
    }

    
Update the system resources configuration if they have previously been initialized.

Hide:
    public static void updateSystemConfiguration(Configuration configDisplayMetrics metrics) {
        if ( != null) {
            .updateConfiguration(configmetrics);
            //Log.i(TAG, "Updated system resources " + mSystem
            //        + ": " + mSystem.getConfiguration());
        }
    }

    
Return the current display metrics that are in effect for this resource object. The returned object should be treated as read-only.

Returns:
The resource's current display metrics.
        return ;
    }

    
Return the current configuration that is in effect for this resource object. The returned object should be treated as read-only.

Returns:
The resource's current configuration.
    public Configuration getConfiguration() {
        return ;
    }
    
    
Return the compatibility mode information for the application. The returned object should be treated as read-only.

Returns:
compatibility info. null if the app does not require compatibility mode.
Hide:
        return ;
    }

    
This is just for testing.

Hide:
    public void setCompatibilityInfo(CompatibilityInfo ci) {
         = ci;
    }
    
    
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.

Parameters:
name The name of the desired resource.
defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
Returns:
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)
    public int getIdentifier(String nameString defTypeString defPackage) {
        try {
            return Integer.parseInt(name);
        } catch (Exception e) {
            // Ignore
        }
        return .getResourceIdentifier(namedefTypedefPackage);
    }

    
Return the full name for a given resource identifier. This name is a single string of the form "package:type/entry".

Parameters:
resid The resource identifier whose name is to be retrieved.
Returns:
A string holding the name of the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getResourcePackageName(int)
getResourceTypeName(int)
getResourceEntryName(int)
    public String getResourceName(int residthrows NotFoundException {
        String str = .getResourceName(resid);
        if (str != nullreturn str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    }
    
    
Return the package name for a given resource identifier.

Parameters:
resid The resource identifier whose package name is to be retrieved.
Returns:
A string holding the package name of the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getResourceName(int)
    public String getResourcePackageName(int residthrows NotFoundException {
        String str = .getResourcePackageName(resid);
        if (str != nullreturn str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    }
    
    
Return the type name for a given resource identifier.

Parameters:
resid The resource identifier whose type name is to be retrieved.
Returns:
A string holding the type name of the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getResourceName(int)
    public String getResourceTypeName(int residthrows NotFoundException {
        String str = .getResourceTypeName(resid);
        if (str != nullreturn str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    }
    
    
Return the entry name for a given resource identifier.

Parameters:
resid The resource identifier whose entry name is to be retrieved.
Returns:
A string holding the entry name of the resource.
Throws:
Resources.NotFoundException Throws NotFoundException if the given ID does not exist.
See also:
getResourceName(int)
    public String getResourceEntryName(int residthrows NotFoundException {
        String str = .getResourceEntryName(resid);
        if (str != nullreturn str;
        throw new NotFoundException("Unable to find resource ID #0x"
                + Integer.toHexString(resid));
    }
    
    
Parse a series of <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 parseBundleExtra(java.lang.String,android.util.AttributeSet,android.os.Bundle) for each extra tag encountered.

Parameters:
parser The parser from which to retrieve the extras.
outBundle A Bundle in which to place all parsed extras.
Throws:
org.xmlpull.v1.XmlPullParserException
java.io.IOException
    public void parseBundleExtras(XmlResourceParser parserBundle outBundle)
            throws XmlPullParserExceptionIOException {
        int outerDepth = parser.getDepth();
        int type;
        while ((type=parser.next()) != .
               && (type != . || parser.getDepth() > outerDepth)) {
            if (type == . || type == .) {
                continue;
            }
            
            String nodeName = parser.getName();
            if (nodeName.equals("extra")) {
                parseBundleExtra("extra"parseroutBundle);
                XmlUtils.skipCurrentTag(parser);
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }        
    }
    
    
Parse a name/value pair out of an XML tag holding that data. The AttributeSet must be holding the data defined by android.R.styleable. The following value types are supported:

Parameters:
tagName The name of the tag these attributes come from; this is only used for reporting error messages.
attrs The attributes from which to retrieve the name/value pair.
outBundle The Bundle in which to place the parsed value.
Throws:
org.xmlpull.v1.XmlPullParserException If the attributes are not valid.
    public void parseBundleExtra(String tagNameAttributeSet attrs,
            Bundle outBundlethrows XmlPullParserException {
        TypedArray sa = obtainAttributes(attrs,
                .....);
        String name = sa.getString(
                .....);
        if (name == null) {
            sa.recycle();
            throw new XmlPullParserException("<" + tagName
                    + "> requires an android:name attribute at "
                    + attrs.getPositionDescription());
        }
        TypedValue v = sa.peekValue(
                .....);
        if (v != null) {
            if (v.type == .) {
                CharSequence cs = v.coerceToString();
                outBundle.putCharSequence(namecs);
            } else if (v.type == .) {
                outBundle.putBoolean(namev.data != 0);
            } else if (v.type >= .
                    && v.type <= .) {
                outBundle.putInt(namev.data);
            } else if (v.type == .) {
                outBundle.putFloat(namev.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();
    }
    
    
Retrieve underlying AssetManager storage for these resources.
    public final AssetManager getAssets() {
        return ;
    }

    
Call this to remove all cached loaded layout resources from the Resources object. Only intended for use with performance testing tools.
    public final void flushLayoutCache() {
        synchronized () {
            // First see if this block is in our cache.
            final int num = .;
            for (int i=0; i<numi++) {
                [i] = -0;
                XmlBlock oldBlock = [i];
                if (oldBlock != null) {
                    oldBlock.close();
                }
                [i] = null;
            }
        }
    }

    
Start preloading of resource data using this Resources object. Only for use by the zygote process for loading common system resources.
    public final void startPreloading() {
        synchronized () {
            if () {
                throw new IllegalStateException("Resources already preloaded");
            }
             = true;
             = true;
        }
    }
    
    
Called by zygote when it is done preloading resources, to change back to normal Resources operation.
    public final void finishPreloading() {
        if () {
             = false;
            flushLayoutCache();
        }
    }
    
    /*package*/ Drawable loadDrawable(TypedValue valueint id)
            throws NotFoundException {
        if () {
            // Log only framework resources
            if ((id >>> 24) == 0x1) {
                final String name = getResourceName(id);
                if (name != null) android.util.Log.d("PreloadDrawable"name);
            }
        }
        final long key = (((longvalue.assetCookie) << 32) | value.data;
        Drawable dr = getCachedDrawable(key);
        if (dr != null) {
            return dr;
        }
        Drawable.ConstantState cs = .get(key);
        if (cs != null) {
            dr = cs.newDrawable(this);
        } else {
            if (value.type >= . &&
                    value.type <= .) {
                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 () Log.v("Loading drawable for cookie "
                        + value.assetCookie + ": " + file);
                if (file.endsWith(".xml")) {
                    try {
                        XmlResourceParser rp = loadXmlResourceParser(
                                fileidvalue.assetCookie"drawable");
                        dr = Drawable.createFromXml(thisrp);
                        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 = .openNonAsset(
                                value.assetCookiefile.);
        //                System.out.println("Opened file " + file + ": " + is);
                        dr = Drawable.createFromResourceStream(thisvalueis,
                                filenull);
                        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 () {
                    .put(keycs);
                } else {
                    synchronized () {
                        //Log.i(TAG, "Saving cached drawable @ #" +
                        //        Integer.toHexString(key.intValue())
                        //        + " in " + this + ": " + cs);
                        .put(keynew WeakReference<Drawable.ConstantState>(cs));
                    }
                }
            }
        }
        return dr;
    }
    private Drawable getCachedDrawable(long key) {
        synchronized () {
            WeakReference<Drawable.ConstantStatewr = .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(this);
                }
                else {  // our entry has been purged
                    .delete(key);
                }
            }
        }
        return null;
    }
    /*package*/ ColorStateList loadColorStateList(TypedValue valueint id)
            throws NotFoundException {
        if () {
            // 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 >= . &&
                value.type <= .) {
            csl = .get(key);
            if (csl != null) {
                return csl;
            }
            csl = ColorStateList.valueOf(value.data);
            if () {
                .put(keycsl);
            }
            return csl;
        }
        csl = getCachedColorStateList(key);
        if (csl != null) {
            return csl;
        }
        csl = .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(
                        fileidvalue.assetCookie"colorstatelist"); 
                csl = ColorStateList.createFromXml(thisrp);
                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 () {
                .put(keycsl);
            } else {
                synchronized () {
                    //Log.i(TAG, "Saving cached color state list @ #" +
                    //        Integer.toHexString(key.intValue())
                    //        + " in " + this + ": " + csl);
                    .put(
                        keynew WeakReference<ColorStateList>(csl));
                }
            }
        }
        return csl;
    }
    private ColorStateList getCachedColorStateList(int key) {
        synchronized () {
            WeakReference<ColorStateListwr = .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
                    .delete(key);
                }
            }
        }
        return null;
    }
    /*package*/ XmlResourceParser loadXmlResourceParser(int idString type)
            throws NotFoundException {
        synchronized () {
            TypedValue value = ;
            getValue(idvaluetrue);
            if (value.type == .) {
                return loadXmlResourceParser(value.string.toString(), id,
                        value.assetCookietype);
            }
            throw new NotFoundException(
                    "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                    + Integer.toHexString(value.type) + " is not valid");
        }
    }
    
    /*package*/ XmlResourceParser loadXmlResourceParser(String fileint id,
            int assetCookieString typethrows NotFoundException {
        if (id != 0) {
            try {
                // These may be compiled...
                synchronized () {
                    // First see if this block is in our cache.
                    final int num = .;
                    for (int i=0; i<numi++) {
                        if ([i] == id) {
                            //System.out.println("**** REUSING XML BLOCK!  id="
                            //                   + id + ", index=" + i);
                            return [i].newParser();
                        }
                    }
                    // Not in the cache, create a new block and put it at
                    // the next slot in the cache.
                    XmlBlock block = .openXmlBlockAsset(
                            assetCookiefile);
                    if (block != null) {
                        int pos = +1;
                        if (pos >= numpos = 0;
                         = pos;
                        XmlBlock oldBlock = [pos];
                        if (oldBlock != null) {
                            oldBlock.close();
                        }
                        [pos] = id;
                        [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));
    }

    
Returns the display adjusted for the Resources' metrics.

Hide:
    public Display getDefaultDisplay(Display defaultDisplay) {
        if ( == null) {
                // the app supports the display. just use the default one.
                 = defaultDisplay;
            } else {
                // display needs adjustment.
                 = Display.createMetricsBasedDisplay(
                        defaultDisplay.getDisplayId(), );
            }
        }
        return ;
    }
    private TypedArray getCachedStyledAttributes(int len) {
        synchronized () {
            TypedArray attrs = ;
            if (attrs != null) {
                 = null;
                attrs.mLength = len;
                int fullLen = len * .;
                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*.],
                    new int[1+len], len);
        }
    }
    private Resources() {
         = 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.
        .setToDefaults();
        updateConfiguration(nullnull);
        .ensureStringBlocks();
    }
New to GrepCode? Check out our FAQ X