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