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