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