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