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