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