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