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