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