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