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 17 package android.content.res; 18 19 import android.animation.Animator; 20 import android.animation.StateListAnimator; 21 import android.annotation.AnimRes; 22 import android.annotation.AnimatorRes; 23 import android.annotation.AnyRes; 24 import android.annotation.ArrayRes; 25 import android.annotation.AttrRes; 26 import android.annotation.BoolRes; 27 import android.annotation.ColorInt; 28 import android.annotation.ColorRes; 29 import android.annotation.DimenRes; 30 import android.annotation.DrawableRes; 31 import android.annotation.FontRes; 32 import android.annotation.FractionRes; 33 import android.annotation.IntegerRes; 34 import android.annotation.LayoutRes; 35 import android.annotation.NonNull; 36 import android.annotation.Nullable; 37 import android.annotation.PluralsRes; 38 import android.annotation.RawRes; 39 import android.annotation.StringRes; 40 import android.annotation.StyleRes; 41 import android.annotation.StyleableRes; 42 import android.annotation.UnsupportedAppUsage; 43 import android.annotation.XmlRes; 44 import android.content.pm.ActivityInfo; 45 import android.content.pm.ActivityInfo.Config; 46 import android.graphics.Movie; 47 import android.graphics.Typeface; 48 import android.graphics.drawable.Drawable; 49 import android.graphics.drawable.Drawable.ConstantState; 50 import android.graphics.drawable.DrawableInflater; 51 import android.os.Build; 52 import android.os.Bundle; 53 import android.util.AttributeSet; 54 import android.util.DisplayMetrics; 55 import android.util.Log; 56 import android.util.LongSparseArray; 57 import android.util.Pools.SynchronizedPool; 58 import android.util.TypedValue; 59 import android.view.DisplayAdjustments; 60 import android.view.ViewDebug; 61 import android.view.ViewHierarchyEncoder; 62 63 import com.android.internal.annotations.VisibleForTesting; 64 import com.android.internal.util.GrowingArrayUtils; 65 import com.android.internal.util.XmlUtils; 66 67 import org.xmlpull.v1.XmlPullParser; 68 import org.xmlpull.v1.XmlPullParserException; 69 70 import java.io.IOException; 71 import java.io.InputStream; 72 import java.lang.ref.WeakReference; 73 import java.util.ArrayList; 74 75 /** 76 * Class for accessing an application's resources. This sits on top of the 77 * asset manager of the application (accessible through {@link #getAssets}) and 78 * provides a high-level API for getting typed data from the assets. 79 * 80 * <p>The Android resource system keeps track of all non-code assets associated with an 81 * application. You can use this class to access your application's resources. You can generally 82 * acquire the {@link android.content.res.Resources} instance associated with your application 83 * with {@link android.content.Context#getResources getResources()}.</p> 84 * 85 * <p>The Android SDK tools compile your application's resources into the application binary 86 * at build time. To use a resource, you must install it correctly in the source tree (inside 87 * your project's {@code res/} directory) and build your application. As part of the build 88 * process, the SDK tools generate symbols for each resource, which you can use in your application 89 * code to access the resources.</p> 90 * 91 * <p>Using application resources makes it easy to update various characteristics of your 92 * application without modifying code, and—by providing sets of alternative 93 * resources—enables you to optimize your application for a variety of device configurations 94 * (such as for different languages and screen sizes). This is an important aspect of developing 95 * Android applications that are compatible on different types of devices.</p> 96 * 97 * <p>For more information about using resources, see the documentation about <a 98 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p> 99 */ 100 public class Resources { 101 /** 102 * The {@code null} resource ID. This denotes an invalid resource ID that is returned by the 103 * system when a resource is not found or the value is set to {@code @null} in XML. 104 */ 105 public static final @AnyRes int ID_NULL = 0; 106 107 static final String TAG = "Resources"; 108 109 private static final Object sSync = new Object(); 110 111 // Used by BridgeResources in layoutlib 112 @UnsupportedAppUsage 113 static Resources mSystem = null; 114 115 @UnsupportedAppUsage 116 private ResourcesImpl mResourcesImpl; 117 118 // Pool of TypedArrays targeted to this Resources object. 119 @UnsupportedAppUsage 120 final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5); 121 122 /** Used to inflate drawable objects from XML. */ 123 @UnsupportedAppUsage 124 private DrawableInflater mDrawableInflater; 125 126 /** Lock object used to protect access to {@link #mTmpValue}. */ 127 private final Object mTmpValueLock = new Object(); 128 129 /** Single-item pool used to minimize TypedValue allocations. */ 130 @UnsupportedAppUsage 131 private TypedValue mTmpValue = new TypedValue(); 132 133 @UnsupportedAppUsage 134 final ClassLoader mClassLoader; 135 136 /** 137 * WeakReferences to Themes that were constructed from this Resources object. 138 * We keep track of these in case our underlying implementation is changed, in which case 139 * the Themes must also get updated ThemeImpls. 140 */ 141 private final ArrayList<WeakReference<Theme>> mThemeRefs = new ArrayList<>(); 142 143 /** 144 * To avoid leaking WeakReferences to garbage collected Themes on the 145 * mThemeRefs list, we flush the list of stale references any time the 146 * mThemeRefNextFlushSize is reached. 147 */ 148 private static final int MIN_THEME_REFS_FLUSH_SIZE = 32; 149 private int mThemeRefsNextFlushSize = MIN_THEME_REFS_FLUSH_SIZE; 150 151 /** 152 * Returns the most appropriate default theme for the specified target SDK version. 153 * <ul> 154 * <li>Below API 11: Gingerbread 155 * <li>APIs 12 thru 14: Holo 156 * <li>APIs 15 thru 23: Device default dark 157 * <li>APIs 24 and above: Device default light with dark action bar 158 * </ul> 159 * 160 * @param curTheme The current theme, or 0 if not specified. 161 * @param targetSdkVersion The target SDK version. 162 * @return A theme resource identifier 163 * @hide 164 */ 165 @UnsupportedAppUsage selectDefaultTheme(int curTheme, int targetSdkVersion)166 public static int selectDefaultTheme(int curTheme, int targetSdkVersion) { 167 return selectSystemTheme(curTheme, targetSdkVersion, 168 com.android.internal.R.style.Theme, 169 com.android.internal.R.style.Theme_Holo, 170 com.android.internal.R.style.Theme_DeviceDefault, 171 com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar); 172 } 173 174 /** @hide */ selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo, int dark, int deviceDefault)175 public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo, 176 int dark, int deviceDefault) { 177 if (curTheme != ID_NULL) { 178 return curTheme; 179 } 180 if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) { 181 return orig; 182 } 183 if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 184 return holo; 185 } 186 if (targetSdkVersion < Build.VERSION_CODES.N) { 187 return dark; 188 } 189 return deviceDefault; 190 } 191 192 /** 193 * Return a global shared Resources object that provides access to only 194 * system resources (no application resources), is not configured for the 195 * current screen (can not use dimension units, does not change based on 196 * orientation, etc), and is not affected by Runtime Resource Overlay. 197 */ getSystem()198 public static Resources getSystem() { 199 synchronized (sSync) { 200 Resources ret = mSystem; 201 if (ret == null) { 202 ret = new Resources(); 203 mSystem = ret; 204 } 205 return ret; 206 } 207 } 208 209 /** 210 * This exception is thrown by the resource APIs when a requested resource 211 * can not be found. 212 */ 213 public static class NotFoundException extends RuntimeException { NotFoundException()214 public NotFoundException() { 215 } 216 NotFoundException(String name)217 public NotFoundException(String name) { 218 super(name); 219 } 220 NotFoundException(String name, Exception cause)221 public NotFoundException(String name, Exception cause) { 222 super(name, cause); 223 } 224 } 225 226 /** 227 * Create a new Resources object on top of an existing set of assets in an 228 * AssetManager. 229 * 230 * @deprecated Resources should not be constructed by apps. 231 * See {@link android.content.Context#createConfigurationContext(Configuration)}. 232 * 233 * @param assets Previously created AssetManager. 234 * @param metrics Current display metrics to consider when 235 * selecting/computing resource values. 236 * @param config Desired device configuration to consider when 237 * selecting/computing resource values (optional). 238 */ 239 @Deprecated Resources(AssetManager assets, DisplayMetrics metrics, Configuration config)240 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) { 241 this(null); 242 mResourcesImpl = new ResourcesImpl(assets, metrics, config, new DisplayAdjustments()); 243 } 244 245 /** 246 * Creates a new Resources object with CompatibilityInfo. 247 * 248 * @param classLoader class loader for the package used to load custom 249 * resource classes, may be {@code null} to use system 250 * class loader 251 * @hide 252 */ 253 @UnsupportedAppUsage Resources(@ullable ClassLoader classLoader)254 public Resources(@Nullable ClassLoader classLoader) { 255 mClassLoader = classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader; 256 } 257 258 /** 259 * Only for creating the System resources. 260 */ 261 @UnsupportedAppUsage Resources()262 private Resources() { 263 this(null); 264 265 final DisplayMetrics metrics = new DisplayMetrics(); 266 metrics.setToDefaults(); 267 268 final Configuration config = new Configuration(); 269 config.setToDefaults(); 270 271 mResourcesImpl = new ResourcesImpl(AssetManager.getSystem(), metrics, config, 272 new DisplayAdjustments()); 273 } 274 275 /** 276 * Set the underlying implementation (containing all the resources and caches) 277 * and updates all Theme references to new implementations as well. 278 * @hide 279 */ 280 @UnsupportedAppUsage setImpl(ResourcesImpl impl)281 public void setImpl(ResourcesImpl impl) { 282 if (impl == mResourcesImpl) { 283 return; 284 } 285 286 mResourcesImpl = impl; 287 288 // Create new ThemeImpls that are identical to the ones we have. 289 synchronized (mThemeRefs) { 290 final int count = mThemeRefs.size(); 291 for (int i = 0; i < count; i++) { 292 WeakReference<Theme> weakThemeRef = mThemeRefs.get(i); 293 Theme theme = weakThemeRef != null ? weakThemeRef.get() : null; 294 if (theme != null) { 295 theme.setImpl(mResourcesImpl.newThemeImpl(theme.getKey())); 296 } 297 } 298 } 299 } 300 301 /** 302 * @hide 303 */ 304 @UnsupportedAppUsage getImpl()305 public ResourcesImpl getImpl() { 306 return mResourcesImpl; 307 } 308 309 /** 310 * @hide 311 */ getClassLoader()312 public ClassLoader getClassLoader() { 313 return mClassLoader; 314 } 315 316 /** 317 * @return the inflater used to create drawable objects 318 * @hide Pending API finalization. 319 */ 320 @UnsupportedAppUsage getDrawableInflater()321 public final DrawableInflater getDrawableInflater() { 322 if (mDrawableInflater == null) { 323 mDrawableInflater = new DrawableInflater(this, mClassLoader); 324 } 325 return mDrawableInflater; 326 } 327 328 /** 329 * Used by AnimatorInflater. 330 * 331 * @hide 332 */ getAnimatorCache()333 public ConfigurationBoundResourceCache<Animator> getAnimatorCache() { 334 return mResourcesImpl.getAnimatorCache(); 335 } 336 337 /** 338 * Used by AnimatorInflater. 339 * 340 * @hide 341 */ getStateListAnimatorCache()342 public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() { 343 return mResourcesImpl.getStateListAnimatorCache(); 344 } 345 346 /** 347 * Return the string value associated with a particular resource ID. The 348 * returned object will be a String if this is a plain string; it will be 349 * some other type of CharSequence if it is styled. 350 * {@more} 351 * 352 * @param id The desired resource identifier, as generated by the aapt 353 * tool. This integer encodes the package, type, and resource 354 * entry. The value 0 is an invalid identifier. 355 * 356 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 357 * 358 * @return CharSequence The string data associated with the resource, plus 359 * possibly styled text information. 360 */ getText(@tringRes int id)361 @NonNull public CharSequence getText(@StringRes int id) throws NotFoundException { 362 CharSequence res = mResourcesImpl.getAssets().getResourceText(id); 363 if (res != null) { 364 return res; 365 } 366 throw new NotFoundException("String resource ID #0x" 367 + Integer.toHexString(id)); 368 } 369 370 /** 371 * Return the Typeface value associated with a particular resource ID. 372 * {@more} 373 * 374 * @param id The desired resource identifier, as generated by the aapt 375 * tool. This integer encodes the package, type, and resource 376 * entry. The value 0 is an invalid identifier. 377 * 378 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 379 * 380 * @return Typeface The Typeface data associated with the resource. 381 */ getFont(@ontRes int id)382 @NonNull public Typeface getFont(@FontRes int id) throws NotFoundException { 383 final TypedValue value = obtainTempTypedValue(); 384 try { 385 final ResourcesImpl impl = mResourcesImpl; 386 impl.getValue(id, value, true); 387 Typeface typeface = impl.loadFont(this, value, id); 388 if (typeface != null) { 389 return typeface; 390 } 391 } finally { 392 releaseTempTypedValue(value); 393 } 394 throw new NotFoundException("Font resource ID #0x" 395 + Integer.toHexString(id)); 396 } 397 398 @NonNull getFont(@onNull TypedValue value, @FontRes int id)399 Typeface getFont(@NonNull TypedValue value, @FontRes int id) throws NotFoundException { 400 return mResourcesImpl.loadFont(this, value, id); 401 } 402 403 /** 404 * @hide 405 */ preloadFonts(@rrayRes int id)406 public void preloadFonts(@ArrayRes int id) { 407 final TypedArray array = obtainTypedArray(id); 408 try { 409 final int size = array.length(); 410 for (int i = 0; i < size; i++) { 411 array.getFont(i); 412 } 413 } finally { 414 array.recycle(); 415 } 416 } 417 418 /** 419 * Returns the character sequence necessary for grammatically correct pluralization 420 * of the given resource ID for the given quantity. 421 * Note that the character sequence is selected based solely on grammatical necessity, 422 * and that such rules differ between languages. Do not assume you know which string 423 * will be returned for a given quantity. See 424 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 425 * for more detail. 426 * 427 * @param id The desired resource identifier, as generated by the aapt 428 * tool. This integer encodes the package, type, and resource 429 * entry. The value 0 is an invalid identifier. 430 * @param quantity The number used to get the correct string for the current language's 431 * plural rules. 432 * 433 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 434 * 435 * @return CharSequence The string data associated with the resource, plus 436 * possibly styled text information. 437 */ 438 @NonNull getQuantityText(@luralsRes int id, int quantity)439 public CharSequence getQuantityText(@PluralsRes int id, int quantity) 440 throws NotFoundException { 441 return mResourcesImpl.getQuantityText(id, quantity); 442 } 443 444 /** 445 * Return the string value associated with a particular resource ID. It 446 * will be stripped of any styled text information. 447 * {@more} 448 * 449 * @param id The desired resource identifier, as generated by the aapt 450 * tool. This integer encodes the package, type, and resource 451 * entry. The value 0 is an invalid identifier. 452 * 453 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 454 * 455 * @return String The string data associated with the resource, 456 * stripped of styled text information. 457 */ 458 @NonNull getString(@tringRes int id)459 public String getString(@StringRes int id) throws NotFoundException { 460 return getText(id).toString(); 461 } 462 463 464 /** 465 * Return the string value associated with a particular resource ID, 466 * substituting the format arguments as defined in {@link java.util.Formatter} 467 * and {@link java.lang.String#format}. It will be stripped of any styled text 468 * information. 469 * {@more} 470 * 471 * @param id The desired resource identifier, as generated by the aapt 472 * tool. This integer encodes the package, type, and resource 473 * entry. The value 0 is an invalid identifier. 474 * 475 * @param formatArgs The format arguments that will be used for substitution. 476 * 477 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 478 * 479 * @return String The string data associated with the resource, 480 * stripped of styled text information. 481 */ 482 @NonNull getString(@tringRes int id, Object... formatArgs)483 public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException { 484 final String raw = getString(id); 485 return String.format(mResourcesImpl.getConfiguration().getLocales().get(0), raw, 486 formatArgs); 487 } 488 489 /** 490 * Formats the string necessary for grammatically correct pluralization 491 * of the given resource ID for the given quantity, using the given arguments. 492 * Note that the string is selected based solely on grammatical necessity, 493 * and that such rules differ between languages. Do not assume you know which string 494 * will be returned for a given quantity. See 495 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 496 * for more detail. 497 * 498 * <p>Substitution of format arguments works as if using 499 * {@link java.util.Formatter} and {@link java.lang.String#format}. 500 * The resulting string will be stripped of any styled text information. 501 * 502 * @param id The desired resource identifier, as generated by the aapt 503 * tool. This integer encodes the package, type, and resource 504 * entry. The value 0 is an invalid identifier. 505 * @param quantity The number used to get the correct string for the current language's 506 * plural rules. 507 * @param formatArgs The format arguments that will be used for substitution. 508 * 509 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 510 * 511 * @return String The string data associated with the resource, 512 * stripped of styled text information. 513 */ 514 @NonNull getQuantityString(@luralsRes int id, int quantity, Object... formatArgs)515 public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs) 516 throws NotFoundException { 517 String raw = getQuantityText(id, quantity).toString(); 518 return String.format(mResourcesImpl.getConfiguration().getLocales().get(0), raw, 519 formatArgs); 520 } 521 522 /** 523 * Returns the string necessary for grammatically correct pluralization 524 * of the given resource ID for the given quantity. 525 * Note that the string is selected based solely on grammatical necessity, 526 * and that such rules differ between languages. Do not assume you know which string 527 * will be returned for a given quantity. See 528 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 529 * for more detail. 530 * 531 * @param id The desired resource identifier, as generated by the aapt 532 * tool. This integer encodes the package, type, and resource 533 * entry. The value 0 is an invalid identifier. 534 * @param quantity The number used to get the correct string for the current language's 535 * plural rules. 536 * 537 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 538 * 539 * @return String The string data associated with the resource, 540 * stripped of styled text information. 541 */ 542 @NonNull getQuantityString(@luralsRes int id, int quantity)543 public String getQuantityString(@PluralsRes int id, int quantity) throws NotFoundException { 544 return getQuantityText(id, quantity).toString(); 545 } 546 547 /** 548 * Return the string value associated with a particular resource ID. The 549 * returned object will be a String if this is a plain string; it will be 550 * some other type of CharSequence if it is styled. 551 * 552 * @param id The desired resource identifier, as generated by the aapt 553 * tool. This integer encodes the package, type, and resource 554 * entry. The value 0 is an invalid identifier. 555 * 556 * @param def The default CharSequence to return. 557 * 558 * @return CharSequence The string data associated with the resource, plus 559 * possibly styled text information, or def if id is 0 or not found. 560 */ getText(@tringRes int id, CharSequence def)561 public CharSequence getText(@StringRes int id, CharSequence def) { 562 CharSequence res = id != 0 ? mResourcesImpl.getAssets().getResourceText(id) : null; 563 return res != null ? res : def; 564 } 565 566 /** 567 * Return the styled text array associated with a particular resource ID. 568 * 569 * @param id The desired resource identifier, as generated by the aapt 570 * tool. This integer encodes the package, type, and resource 571 * entry. The value 0 is an invalid identifier. 572 * 573 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 574 * 575 * @return The styled text array associated with the resource. 576 */ 577 @NonNull getTextArray(@rrayRes int id)578 public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException { 579 CharSequence[] res = mResourcesImpl.getAssets().getResourceTextArray(id); 580 if (res != null) { 581 return res; 582 } 583 throw new NotFoundException("Text array resource ID #0x" + Integer.toHexString(id)); 584 } 585 586 /** 587 * Return the string array associated with a particular resource ID. 588 * 589 * @param id The desired resource identifier, as generated by the aapt 590 * tool. This integer encodes the package, type, and resource 591 * entry. The value 0 is an invalid identifier. 592 * 593 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 594 * 595 * @return The string array associated with the resource. 596 */ 597 @NonNull getStringArray(@rrayRes int id)598 public String[] getStringArray(@ArrayRes int id) 599 throws NotFoundException { 600 String[] res = mResourcesImpl.getAssets().getResourceStringArray(id); 601 if (res != null) { 602 return res; 603 } 604 throw new NotFoundException("String array resource ID #0x" + Integer.toHexString(id)); 605 } 606 607 /** 608 * Return the int array associated with a particular resource ID. 609 * 610 * @param id The desired resource identifier, as generated by the aapt 611 * tool. This integer encodes the package, type, and resource 612 * entry. The value 0 is an invalid identifier. 613 * 614 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 615 * 616 * @return The int array associated with the resource. 617 */ 618 @NonNull getIntArray(@rrayRes int id)619 public int[] getIntArray(@ArrayRes int id) throws NotFoundException { 620 int[] res = mResourcesImpl.getAssets().getResourceIntArray(id); 621 if (res != null) { 622 return res; 623 } 624 throw new NotFoundException("Int array resource ID #0x" + Integer.toHexString(id)); 625 } 626 627 /** 628 * Return an array of heterogeneous values. 629 * 630 * @param id The desired resource identifier, as generated by the aapt 631 * tool. This integer encodes the package, type, and resource 632 * entry. The value 0 is an invalid identifier. 633 * 634 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 635 * 636 * @return Returns a TypedArray holding an array of the array values. 637 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 638 * when done with it. 639 */ 640 @NonNull obtainTypedArray(@rrayRes int id)641 public TypedArray obtainTypedArray(@ArrayRes int id) throws NotFoundException { 642 final ResourcesImpl impl = mResourcesImpl; 643 int len = impl.getAssets().getResourceArraySize(id); 644 if (len < 0) { 645 throw new NotFoundException("Array resource ID #0x" + Integer.toHexString(id)); 646 } 647 648 TypedArray array = TypedArray.obtain(this, len); 649 array.mLength = impl.getAssets().getResourceArray(id, array.mData); 650 array.mIndices[0] = 0; 651 652 return array; 653 } 654 655 /** 656 * Retrieve a dimensional for a particular resource ID. Unit 657 * conversions are based on the current {@link DisplayMetrics} associated 658 * with the resources. 659 * 660 * @param id The desired resource identifier, as generated by the aapt 661 * tool. This integer encodes the package, type, and resource 662 * entry. The value 0 is an invalid identifier. 663 * 664 * @return Resource dimension value multiplied by the appropriate metric to convert to pixels. 665 * 666 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 667 * 668 * @see #getDimensionPixelOffset 669 * @see #getDimensionPixelSize 670 */ getDimension(@imenRes int id)671 public float getDimension(@DimenRes int id) throws NotFoundException { 672 final TypedValue value = obtainTempTypedValue(); 673 try { 674 final ResourcesImpl impl = mResourcesImpl; 675 impl.getValue(id, value, true); 676 if (value.type == TypedValue.TYPE_DIMENSION) { 677 return TypedValue.complexToDimension(value.data, impl.getDisplayMetrics()); 678 } 679 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 680 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 681 } finally { 682 releaseTempTypedValue(value); 683 } 684 } 685 686 /** 687 * Retrieve a dimensional for a particular resource ID for use 688 * as an offset in raw pixels. This is the same as 689 * {@link #getDimension}, except the returned value is converted to 690 * integer pixels for you. An offset conversion involves simply 691 * truncating the base value to an integer. 692 * 693 * @param id The desired resource identifier, as generated by the aapt 694 * tool. This integer encodes the package, type, and resource 695 * entry. The value 0 is an invalid identifier. 696 * 697 * @return Resource dimension value multiplied by the appropriate 698 * metric and truncated to integer pixels. 699 * 700 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 701 * 702 * @see #getDimension 703 * @see #getDimensionPixelSize 704 */ getDimensionPixelOffset(@imenRes int id)705 public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException { 706 final TypedValue value = obtainTempTypedValue(); 707 try { 708 final ResourcesImpl impl = mResourcesImpl; 709 impl.getValue(id, value, true); 710 if (value.type == TypedValue.TYPE_DIMENSION) { 711 return TypedValue.complexToDimensionPixelOffset(value.data, 712 impl.getDisplayMetrics()); 713 } 714 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 715 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 716 } finally { 717 releaseTempTypedValue(value); 718 } 719 } 720 721 /** 722 * Retrieve a dimensional for a particular resource ID for use 723 * as a size in raw pixels. This is the same as 724 * {@link #getDimension}, except the returned value is converted to 725 * integer pixels for use as a size. A size conversion involves 726 * rounding the base value, and ensuring that a non-zero base value 727 * is at least one pixel in size. 728 * 729 * @param id The desired resource identifier, as generated by the aapt 730 * tool. This integer encodes the package, type, and resource 731 * entry. The value 0 is an invalid identifier. 732 * 733 * @return Resource dimension value multiplied by the appropriate 734 * metric and truncated to integer pixels. 735 * 736 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 737 * 738 * @see #getDimension 739 * @see #getDimensionPixelOffset 740 */ getDimensionPixelSize(@imenRes int id)741 public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException { 742 final TypedValue value = obtainTempTypedValue(); 743 try { 744 final ResourcesImpl impl = mResourcesImpl; 745 impl.getValue(id, value, true); 746 if (value.type == TypedValue.TYPE_DIMENSION) { 747 return TypedValue.complexToDimensionPixelSize(value.data, impl.getDisplayMetrics()); 748 } 749 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 750 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 751 } finally { 752 releaseTempTypedValue(value); 753 } 754 } 755 756 /** 757 * Retrieve a fractional unit for a particular resource ID. 758 * 759 * @param id The desired resource identifier, as generated by the aapt 760 * tool. This integer encodes the package, type, and resource 761 * entry. The value 0 is an invalid identifier. 762 * @param base The base value of this fraction. In other words, a 763 * standard fraction is multiplied by this value. 764 * @param pbase The parent base value of this fraction. In other 765 * words, a parent fraction (nn%p) is multiplied by this 766 * value. 767 * 768 * @return Attribute fractional value multiplied by the appropriate 769 * base value. 770 * 771 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 772 */ getFraction(@ractionRes int id, int base, int pbase)773 public float getFraction(@FractionRes int id, int base, int pbase) { 774 final TypedValue value = obtainTempTypedValue(); 775 try { 776 mResourcesImpl.getValue(id, value, true); 777 if (value.type == TypedValue.TYPE_FRACTION) { 778 return TypedValue.complexToFraction(value.data, base, pbase); 779 } 780 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 781 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 782 } finally { 783 releaseTempTypedValue(value); 784 } 785 } 786 787 /** 788 * Return a drawable object associated with a particular resource ID. 789 * Various types of objects will be returned depending on the underlying 790 * resource -- for example, a solid color, PNG image, scalable image, etc. 791 * The Drawable API hides these implementation details. 792 * 793 * <p class="note"><strong>Note:</strong> Prior to 794 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function 795 * would not correctly retrieve the final configuration density when 796 * the resource ID passed here is an alias to another Drawable resource. 797 * This means that if the density configuration of the alias resource 798 * is different than the actual resource, the density of the returned 799 * Drawable would be incorrect, resulting in bad scaling. To work 800 * around this, you can instead manually resolve the aliased reference 801 * by using {@link #getValue(int, TypedValue, boolean)} and passing 802 * {@code true} for {@code resolveRefs}. The resulting 803 * {@link TypedValue#resourceId} value may be passed to this method.</p> 804 * 805 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use 806 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)} 807 * or {@link #getDrawable(int, Theme)} passing the desired theme.</p> 808 * 809 * @param id The desired resource identifier, as generated by the aapt 810 * tool. This integer encodes the package, type, and resource 811 * entry. The value 0 is an invalid identifier. 812 * @return Drawable An object that can be used to draw this resource. 813 * @throws NotFoundException Throws NotFoundException if the given ID does 814 * not exist. 815 * @see #getDrawable(int, Theme) 816 * @deprecated Use {@link #getDrawable(int, Theme)} instead. 817 */ 818 @Deprecated getDrawable(@rawableRes int id)819 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException { 820 final Drawable d = getDrawable(id, null); 821 if (d != null && d.canApplyTheme()) { 822 Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme " 823 + "attributes! Consider using Resources.getDrawable(int, Theme) or " 824 + "Context.getDrawable(int).", new RuntimeException()); 825 } 826 return d; 827 } 828 829 /** 830 * Return a drawable object associated with a particular resource ID and 831 * styled for the specified theme. Various types of objects will be 832 * returned depending on the underlying resource -- for example, a solid 833 * color, PNG image, scalable image, etc. 834 * 835 * @param id The desired resource identifier, as generated by the aapt 836 * tool. This integer encodes the package, type, and resource 837 * entry. The value 0 is an invalid identifier. 838 * @param theme The theme used to style the drawable attributes, may be {@code null}. 839 * @return Drawable An object that can be used to draw this resource. 840 * @throws NotFoundException Throws NotFoundException if the given ID does 841 * not exist. 842 */ getDrawable(@rawableRes int id, @Nullable Theme theme)843 public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme) 844 throws NotFoundException { 845 return getDrawableForDensity(id, 0, theme); 846 } 847 848 /** 849 * Return a drawable object associated with a particular resource ID for the 850 * given screen density in DPI. This will set the drawable's density to be 851 * the device's density multiplied by the ratio of actual drawable density 852 * to requested density. This allows the drawable to be scaled up to the 853 * correct size if needed. Various types of objects will be returned 854 * depending on the underlying resource -- for example, a solid color, PNG 855 * image, scalable image, etc. The Drawable API hides these implementation 856 * details. 857 * 858 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use 859 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)} 860 * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired 861 * theme.</p> 862 * 863 * @param id The desired resource identifier, as generated by the aapt tool. 864 * This integer encodes the package, type, and resource entry. 865 * The value 0 is an invalid identifier. 866 * @param density the desired screen density indicated by the resource as 867 * found in {@link DisplayMetrics}. A value of 0 means to use the 868 * density returned from {@link #getConfiguration()}. 869 * This is equivalent to calling {@link #getDrawable(int)}. 870 * @return Drawable An object that can be used to draw this resource. 871 * @throws NotFoundException Throws NotFoundException if the given ID does 872 * not exist. 873 * @see #getDrawableForDensity(int, int, Theme) 874 * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead. 875 */ 876 @Nullable 877 @Deprecated getDrawableForDensity(@rawableRes int id, int density)878 public Drawable getDrawableForDensity(@DrawableRes int id, int density) 879 throws NotFoundException { 880 return getDrawableForDensity(id, density, null); 881 } 882 883 /** 884 * Return a drawable object associated with a particular resource ID for the 885 * given screen density in DPI and styled for the specified theme. 886 * 887 * @param id The desired resource identifier, as generated by the aapt tool. 888 * This integer encodes the package, type, and resource entry. 889 * The value 0 is an invalid identifier. 890 * @param density The desired screen density indicated by the resource as 891 * found in {@link DisplayMetrics}. A value of 0 means to use the 892 * density returned from {@link #getConfiguration()}. 893 * This is equivalent to calling {@link #getDrawable(int, Theme)}. 894 * @param theme The theme used to style the drawable attributes, may be {@code null} if the 895 * drawable cannot be decoded. 896 * @return Drawable An object that can be used to draw this resource. 897 * @throws NotFoundException Throws NotFoundException if the given ID does 898 * not exist. 899 */ 900 @Nullable getDrawableForDensity(@rawableRes int id, int density, @Nullable Theme theme)901 public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) { 902 final TypedValue value = obtainTempTypedValue(); 903 try { 904 final ResourcesImpl impl = mResourcesImpl; 905 impl.getValueForDensity(id, density, value, true); 906 return impl.loadDrawable(this, value, id, density, theme); 907 } finally { 908 releaseTempTypedValue(value); 909 } 910 } 911 912 @NonNull 913 @UnsupportedAppUsage loadDrawable(@onNull TypedValue value, int id, int density, @Nullable Theme theme)914 Drawable loadDrawable(@NonNull TypedValue value, int id, int density, @Nullable Theme theme) 915 throws NotFoundException { 916 return mResourcesImpl.loadDrawable(this, value, id, density, theme); 917 } 918 919 /** 920 * Return a movie object associated with the particular resource ID. 921 * @param id The desired resource identifier, as generated by the aapt 922 * tool. This integer encodes the package, type, and resource 923 * entry. The value 0 is an invalid identifier. 924 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 925 * 926 * @deprecated Prefer {@link android.graphics.drawable.AnimatedImageDrawable}. 927 */ 928 @Deprecated getMovie(@awRes int id)929 public Movie getMovie(@RawRes int id) throws NotFoundException { 930 final InputStream is = openRawResource(id); 931 final Movie movie = Movie.decodeStream(is); 932 try { 933 is.close(); 934 } catch (IOException e) { 935 // No one cares. 936 } 937 return movie; 938 } 939 940 /** 941 * Returns a color integer associated with a particular resource ID. If the 942 * resource holds a complex {@link ColorStateList}, then the default color 943 * from the set is returned. 944 * 945 * @param id The desired resource identifier, as generated by the aapt 946 * tool. This integer encodes the package, type, and resource 947 * entry. The value 0 is an invalid identifier. 948 * 949 * @throws NotFoundException Throws NotFoundException if the given ID does 950 * not exist. 951 * 952 * @return A single color value in the form 0xAARRGGBB. 953 * @deprecated Use {@link #getColor(int, Theme)} instead. 954 */ 955 @ColorInt 956 @Deprecated getColor(@olorRes int id)957 public int getColor(@ColorRes int id) throws NotFoundException { 958 return getColor(id, null); 959 } 960 961 /** 962 * Returns a themed color integer associated with a particular resource ID. 963 * If the resource holds a complex {@link ColorStateList}, then the default 964 * color from the set is returned. 965 * 966 * @param id The desired resource identifier, as generated by the aapt 967 * tool. This integer encodes the package, type, and resource 968 * entry. The value 0 is an invalid identifier. 969 * @param theme The theme used to style the color attributes, may be 970 * {@code null}. 971 * 972 * @throws NotFoundException Throws NotFoundException if the given ID does 973 * not exist. 974 * 975 * @return A single color value in the form 0xAARRGGBB. 976 */ 977 @ColorInt getColor(@olorRes int id, @Nullable Theme theme)978 public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException { 979 final TypedValue value = obtainTempTypedValue(); 980 try { 981 final ResourcesImpl impl = mResourcesImpl; 982 impl.getValue(id, value, true); 983 if (value.type >= TypedValue.TYPE_FIRST_INT 984 && value.type <= TypedValue.TYPE_LAST_INT) { 985 return value.data; 986 } else if (value.type != TypedValue.TYPE_STRING) { 987 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 988 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 989 } 990 991 final ColorStateList csl = impl.loadColorStateList(this, value, id, theme); 992 return csl.getDefaultColor(); 993 } finally { 994 releaseTempTypedValue(value); 995 } 996 } 997 998 /** 999 * Returns a color state list associated with a particular resource ID. The 1000 * resource may contain either a single raw color value or a complex 1001 * {@link ColorStateList} holding multiple possible colors. 1002 * 1003 * @param id The desired resource identifier of a {@link ColorStateList}, 1004 * as generated by the aapt tool. This integer encodes the 1005 * package, type, and resource entry. The value 0 is an invalid 1006 * identifier. 1007 * 1008 * @throws NotFoundException Throws NotFoundException if the given ID does 1009 * not exist. 1010 * 1011 * @return A ColorStateList object containing either a single solid color 1012 * or multiple colors that can be selected based on a state. 1013 * @deprecated Use {@link #getColorStateList(int, Theme)} instead. 1014 */ 1015 @NonNull 1016 @Deprecated getColorStateList(@olorRes int id)1017 public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException { 1018 final ColorStateList csl = getColorStateList(id, null); 1019 if (csl != null && csl.canApplyTheme()) { 1020 Log.w(TAG, "ColorStateList " + getResourceName(id) + " has " 1021 + "unresolved theme attributes! Consider using " 1022 + "Resources.getColorStateList(int, Theme) or " 1023 + "Context.getColorStateList(int).", new RuntimeException()); 1024 } 1025 return csl; 1026 } 1027 1028 /** 1029 * Returns a themed color state list associated with a particular resource 1030 * ID. The resource may contain either a single raw color value or a 1031 * complex {@link ColorStateList} holding multiple possible colors. 1032 * 1033 * @param id The desired resource identifier of a {@link ColorStateList}, 1034 * as generated by the aapt tool. This integer encodes the 1035 * package, type, and resource entry. The value 0 is an invalid 1036 * identifier. 1037 * @param theme The theme used to style the color attributes, may be 1038 * {@code null}. 1039 * 1040 * @throws NotFoundException Throws NotFoundException if the given ID does 1041 * not exist. 1042 * 1043 * @return A themed ColorStateList object containing either a single solid 1044 * color or multiple colors that can be selected based on a state. 1045 */ 1046 @NonNull getColorStateList(@olorRes int id, @Nullable Theme theme)1047 public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme) 1048 throws NotFoundException { 1049 final TypedValue value = obtainTempTypedValue(); 1050 try { 1051 final ResourcesImpl impl = mResourcesImpl; 1052 impl.getValue(id, value, true); 1053 return impl.loadColorStateList(this, value, id, theme); 1054 } finally { 1055 releaseTempTypedValue(value); 1056 } 1057 } 1058 1059 @NonNull loadColorStateList(@onNull TypedValue value, int id, @Nullable Theme theme)1060 ColorStateList loadColorStateList(@NonNull TypedValue value, int id, @Nullable Theme theme) 1061 throws NotFoundException { 1062 return mResourcesImpl.loadColorStateList(this, value, id, theme); 1063 } 1064 1065 /** 1066 * @hide 1067 */ 1068 @NonNull loadComplexColor(@onNull TypedValue value, int id, @Nullable Theme theme)1069 public ComplexColor loadComplexColor(@NonNull TypedValue value, int id, @Nullable Theme theme) { 1070 return mResourcesImpl.loadComplexColor(this, value, id, theme); 1071 } 1072 1073 /** 1074 * Return a boolean associated with a particular resource ID. This can be 1075 * used with any integral resource value, and will return true if it is 1076 * non-zero. 1077 * 1078 * @param id The desired resource identifier, as generated by the aapt 1079 * tool. This integer encodes the package, type, and resource 1080 * entry. The value 0 is an invalid identifier. 1081 * 1082 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1083 * 1084 * @return Returns the boolean value contained in the resource. 1085 */ getBoolean(@oolRes int id)1086 public boolean getBoolean(@BoolRes int id) throws NotFoundException { 1087 final TypedValue value = obtainTempTypedValue(); 1088 try { 1089 mResourcesImpl.getValue(id, value, true); 1090 if (value.type >= TypedValue.TYPE_FIRST_INT 1091 && value.type <= TypedValue.TYPE_LAST_INT) { 1092 return value.data != 0; 1093 } 1094 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 1095 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 1096 } finally { 1097 releaseTempTypedValue(value); 1098 } 1099 } 1100 1101 /** 1102 * Return an integer associated with a particular resource ID. 1103 * 1104 * @param id The desired resource identifier, as generated by the aapt 1105 * tool. This integer encodes the package, type, and resource 1106 * entry. The value 0 is an invalid identifier. 1107 * 1108 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1109 * 1110 * @return Returns the integer value contained in the resource. 1111 */ getInteger(@ntegerRes int id)1112 public int getInteger(@IntegerRes int id) throws NotFoundException { 1113 final TypedValue value = obtainTempTypedValue(); 1114 try { 1115 mResourcesImpl.getValue(id, value, true); 1116 if (value.type >= TypedValue.TYPE_FIRST_INT 1117 && value.type <= TypedValue.TYPE_LAST_INT) { 1118 return value.data; 1119 } 1120 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 1121 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 1122 } finally { 1123 releaseTempTypedValue(value); 1124 } 1125 } 1126 1127 /** 1128 * Retrieve a floating-point value for a particular resource ID. 1129 * 1130 * @param id The desired resource identifier, as generated by the aapt 1131 * tool. This integer encodes the package, type, and resource 1132 * entry. The value 0 is an invalid identifier. 1133 * 1134 * @return Returns the floating-point value contained in the resource. 1135 * 1136 * @throws NotFoundException Throws NotFoundException if the given ID does 1137 * not exist or is not a floating-point value. 1138 */ getFloat(@imenRes int id)1139 public float getFloat(@DimenRes int id) { 1140 final TypedValue value = obtainTempTypedValue(); 1141 try { 1142 mResourcesImpl.getValue(id, value, true); 1143 if (value.type == TypedValue.TYPE_FLOAT) { 1144 return value.getFloat(); 1145 } 1146 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 1147 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 1148 } finally { 1149 releaseTempTypedValue(value); 1150 } 1151 } 1152 1153 /** 1154 * Return an XmlResourceParser through which you can read a view layout 1155 * description for the given resource ID. This parser has limited 1156 * functionality -- in particular, you can't change its input, and only 1157 * the high-level events are available. 1158 * 1159 * <p>This function is really a simple wrapper for calling 1160 * {@link #getXml} with a layout resource. 1161 * 1162 * @param id The desired resource identifier, as generated by the aapt 1163 * tool. This integer encodes the package, type, and resource 1164 * entry. The value 0 is an invalid identifier. 1165 * 1166 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1167 * 1168 * @return A new parser object through which you can read 1169 * the XML data. 1170 * 1171 * @see #getXml 1172 */ 1173 @NonNull getLayout(@ayoutRes int id)1174 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException { 1175 return loadXmlResourceParser(id, "layout"); 1176 } 1177 1178 /** 1179 * Return an XmlResourceParser through which you can read an animation 1180 * description for the given resource ID. This parser has limited 1181 * functionality -- in particular, you can't change its input, and only 1182 * the high-level events are available. 1183 * 1184 * <p>This function is really a simple wrapper for calling 1185 * {@link #getXml} with an animation resource. 1186 * 1187 * @param id The desired resource identifier, as generated by the aapt 1188 * tool. This integer encodes the package, type, and resource 1189 * entry. The value 0 is an invalid identifier. 1190 * 1191 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1192 * 1193 * @return A new parser object through which you can read 1194 * the XML data. 1195 * 1196 * @see #getXml 1197 */ 1198 @NonNull getAnimation(@nimatorRes @nimRes int id)1199 public XmlResourceParser getAnimation(@AnimatorRes @AnimRes int id) throws NotFoundException { 1200 return loadXmlResourceParser(id, "anim"); 1201 } 1202 1203 /** 1204 * Return an XmlResourceParser through which you can read a generic XML 1205 * resource for the given resource ID. 1206 * 1207 * <p>The XmlPullParser implementation returned here has some limited 1208 * functionality. In particular, you can't change its input, and only 1209 * high-level parsing events are available (since the document was 1210 * pre-parsed for you at build time, which involved merging text and 1211 * stripping comments). 1212 * 1213 * @param id The desired resource identifier, as generated by the aapt 1214 * tool. This integer encodes the package, type, and resource 1215 * entry. The value 0 is an invalid identifier. 1216 * 1217 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1218 * 1219 * @return A new parser object through which you can read 1220 * the XML data. 1221 * 1222 * @see android.util.AttributeSet 1223 */ 1224 @NonNull getXml(@mlRes int id)1225 public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException { 1226 return loadXmlResourceParser(id, "xml"); 1227 } 1228 1229 /** 1230 * Open a data stream for reading a raw resource. This can only be used 1231 * with resources whose value is the name of an asset files -- that is, it can be 1232 * used to open drawable, sound, and raw resources; it will fail on string 1233 * and color resources. 1234 * 1235 * @param id The resource identifier to open, as generated by the aapt tool. 1236 * 1237 * @return InputStream Access to the resource data. 1238 * 1239 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1240 */ 1241 @NonNull openRawResource(@awRes int id)1242 public InputStream openRawResource(@RawRes int id) throws NotFoundException { 1243 final TypedValue value = obtainTempTypedValue(); 1244 try { 1245 return openRawResource(id, value); 1246 } finally { 1247 releaseTempTypedValue(value); 1248 } 1249 } 1250 1251 /** 1252 * Returns a TypedValue suitable for temporary use. The obtained TypedValue 1253 * should be released using {@link #releaseTempTypedValue(TypedValue)}. 1254 * 1255 * @return a typed value suitable for temporary use 1256 */ obtainTempTypedValue()1257 private TypedValue obtainTempTypedValue() { 1258 TypedValue tmpValue = null; 1259 synchronized (mTmpValueLock) { 1260 if (mTmpValue != null) { 1261 tmpValue = mTmpValue; 1262 mTmpValue = null; 1263 } 1264 } 1265 if (tmpValue == null) { 1266 return new TypedValue(); 1267 } 1268 return tmpValue; 1269 } 1270 1271 /** 1272 * Returns a TypedValue to the pool. After calling this method, the 1273 * specified TypedValue should no longer be accessed. 1274 * 1275 * @param value the typed value to return to the pool 1276 */ releaseTempTypedValue(TypedValue value)1277 private void releaseTempTypedValue(TypedValue value) { 1278 synchronized (mTmpValueLock) { 1279 if (mTmpValue == null) { 1280 mTmpValue = value; 1281 } 1282 } 1283 } 1284 1285 /** 1286 * Open a data stream for reading a raw resource. This can only be used 1287 * with resources whose value is the name of an asset file -- that is, it can be 1288 * used to open drawable, sound, and raw resources; it will fail on string 1289 * and color resources. 1290 * 1291 * @param id The resource identifier to open, as generated by the aapt tool. 1292 * @param value The TypedValue object to hold the resource information. 1293 * 1294 * @return InputStream Access to the resource data. 1295 * 1296 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1297 */ 1298 @NonNull openRawResource(@awRes int id, TypedValue value)1299 public InputStream openRawResource(@RawRes int id, TypedValue value) 1300 throws NotFoundException { 1301 return mResourcesImpl.openRawResource(id, value); 1302 } 1303 1304 /** 1305 * Open a file descriptor for reading a raw resource. This can only be used 1306 * with resources whose value is the name of an asset files -- that is, it can be 1307 * used to open drawable, sound, and raw resources; it will fail on string 1308 * and color resources. 1309 * 1310 * <p>This function only works for resources that are stored in the package 1311 * as uncompressed data, which typically includes things like mp3 files 1312 * and png images. 1313 * 1314 * @param id The resource identifier to open, as generated by the aapt tool. 1315 * 1316 * @return AssetFileDescriptor A new file descriptor you can use to read 1317 * the resource. This includes the file descriptor itself, as well as the 1318 * offset and length of data where the resource appears in the file. A 1319 * null is returned if the file exists but is compressed. 1320 * 1321 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1322 * 1323 */ openRawResourceFd(@awRes int id)1324 public AssetFileDescriptor openRawResourceFd(@RawRes int id) 1325 throws NotFoundException { 1326 final TypedValue value = obtainTempTypedValue(); 1327 try { 1328 return mResourcesImpl.openRawResourceFd(id, value); 1329 } finally { 1330 releaseTempTypedValue(value); 1331 } 1332 } 1333 1334 /** 1335 * Return the raw data associated with a particular resource ID. 1336 * 1337 * @param id The desired resource identifier, as generated by the aapt 1338 * tool. This integer encodes the package, type, and resource 1339 * entry. The value 0 is an invalid identifier. 1340 * @param outValue Object in which to place the resource data. 1341 * @param resolveRefs If true, a resource that is a reference to another 1342 * resource will be followed so that you receive the 1343 * actual final resource data. If false, the TypedValue 1344 * will be filled in with the reference itself. 1345 * 1346 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1347 * 1348 */ getValue(@nyRes int id, TypedValue outValue, boolean resolveRefs)1349 public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs) 1350 throws NotFoundException { 1351 mResourcesImpl.getValue(id, outValue, resolveRefs); 1352 } 1353 1354 /** 1355 * Get the raw value associated with a resource with associated density. 1356 * 1357 * @param id resource identifier 1358 * @param density density in DPI 1359 * @param resolveRefs If true, a resource that is a reference to another 1360 * resource will be followed so that you receive the actual final 1361 * resource data. If false, the TypedValue will be filled in with 1362 * the reference itself. 1363 * @throws NotFoundException Throws NotFoundException if the given ID does 1364 * not exist. 1365 * @see #getValue(String, TypedValue, boolean) 1366 */ getValueForDensity(@nyRes int id, int density, TypedValue outValue, boolean resolveRefs)1367 public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue, 1368 boolean resolveRefs) throws NotFoundException { 1369 mResourcesImpl.getValueForDensity(id, density, outValue, resolveRefs); 1370 } 1371 1372 /** 1373 * Return the raw data associated with a particular resource ID. 1374 * See getIdentifier() for information on how names are mapped to resource 1375 * IDs, and getString(int) for information on how string resources are 1376 * retrieved. 1377 * 1378 * <p>Note: use of this function is discouraged. It is much more 1379 * efficient to retrieve resources by identifier than by name. 1380 * 1381 * @param name The name of the desired resource. This is passed to 1382 * getIdentifier() with a default type of "string". 1383 * @param outValue Object in which to place the resource data. 1384 * @param resolveRefs If true, a resource that is a reference to another 1385 * resource will be followed so that you receive the 1386 * actual final resource data. If false, the TypedValue 1387 * will be filled in with the reference itself. 1388 * 1389 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1390 * 1391 */ getValue(String name, TypedValue outValue, boolean resolveRefs)1392 public void getValue(String name, TypedValue outValue, boolean resolveRefs) 1393 throws NotFoundException { 1394 mResourcesImpl.getValue(name, outValue, resolveRefs); 1395 } 1396 1397 1398 /** 1399 * Returns the resource ID of the resource that was used to create this AttributeSet. 1400 * 1401 * @param set AttributeSet for which we want to find the source. 1402 * @return The resource ID for the source that is backing the given AttributeSet or 1403 * {@link Resources#ID_NULL} if the AttributeSet is {@code null}. 1404 */ 1405 @AnyRes getAttributeSetSourceResId(@ullable AttributeSet set)1406 public static int getAttributeSetSourceResId(@Nullable AttributeSet set) { 1407 return ResourcesImpl.getAttributeSetSourceResId(set); 1408 } 1409 1410 /** 1411 * This class holds the current attribute values for a particular theme. 1412 * In other words, a Theme is a set of values for resource attributes; 1413 * these are used in conjunction with {@link TypedArray} 1414 * to resolve the final value for an attribute. 1415 * 1416 * <p>The Theme's attributes come into play in two ways: (1) a styled 1417 * attribute can explicit reference a value in the theme through the 1418 * "?themeAttribute" syntax; (2) if no value has been defined for a 1419 * particular styled attribute, as a last resort we will try to find that 1420 * attribute's value in the Theme. 1421 * 1422 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to 1423 * retrieve XML attributes with style and theme information applied. 1424 */ 1425 public final class Theme { 1426 @UnsupportedAppUsage 1427 private ResourcesImpl.ThemeImpl mThemeImpl; 1428 Theme()1429 private Theme() { 1430 } 1431 setImpl(ResourcesImpl.ThemeImpl impl)1432 void setImpl(ResourcesImpl.ThemeImpl impl) { 1433 mThemeImpl = impl; 1434 } 1435 1436 /** 1437 * Place new attribute values into the theme. The style resource 1438 * specified by <var>resid</var> will be retrieved from this Theme's 1439 * resources, its values placed into the Theme object. 1440 * 1441 * <p>The semantics of this function depends on the <var>force</var> 1442 * argument: If false, only values that are not already defined in 1443 * the theme will be copied from the system resource; otherwise, if 1444 * any of the style's attributes are already defined in the theme, the 1445 * current values in the theme will be overwritten. 1446 * 1447 * @param resId The resource ID of a style resource from which to 1448 * obtain attribute values. 1449 * @param force If true, values in the style resource will always be 1450 * used in the theme; otherwise, they will only be used 1451 * if not already defined in the theme. 1452 */ applyStyle(int resId, boolean force)1453 public void applyStyle(int resId, boolean force) { 1454 mThemeImpl.applyStyle(resId, force); 1455 } 1456 1457 /** 1458 * Set this theme to hold the same contents as the theme 1459 * <var>other</var>. If both of these themes are from the same 1460 * Resources object, they will be identical after this function 1461 * returns. If they are from different Resources, only the resources 1462 * they have in common will be set in this theme. 1463 * 1464 * @param other The existing Theme to copy from. 1465 */ setTo(Theme other)1466 public void setTo(Theme other) { 1467 mThemeImpl.setTo(other.mThemeImpl); 1468 } 1469 1470 /** 1471 * Return a TypedArray holding the values defined by 1472 * <var>Theme</var> which are listed in <var>attrs</var>. 1473 * 1474 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1475 * with the array. 1476 * 1477 * @param attrs The desired attributes. These attribute IDs must be sorted in ascending 1478 * order. 1479 * 1480 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1481 * 1482 * @return Returns a TypedArray holding an array of the attribute values. 1483 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1484 * when done with it. 1485 * 1486 * @see Resources#obtainAttributes 1487 * @see #obtainStyledAttributes(int, int[]) 1488 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 1489 */ 1490 @NonNull obtainStyledAttributes(@onNull @tyleableRes int[] attrs)1491 public TypedArray obtainStyledAttributes(@NonNull @StyleableRes int[] attrs) { 1492 return mThemeImpl.obtainStyledAttributes(this, null, attrs, 0, 0); 1493 } 1494 1495 /** 1496 * Return a TypedArray holding the values defined by the style 1497 * resource <var>resid</var> which are listed in <var>attrs</var>. 1498 * 1499 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1500 * with the array. 1501 * 1502 * @param resId The desired style resource. 1503 * @param attrs The desired attributes in the style. These attribute IDs must be sorted in 1504 * ascending order. 1505 * 1506 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1507 * 1508 * @return Returns a TypedArray holding an array of the attribute values. 1509 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1510 * when done with it. 1511 * 1512 * @see Resources#obtainAttributes 1513 * @see #obtainStyledAttributes(int[]) 1514 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 1515 */ 1516 @NonNull obtainStyledAttributes(@tyleRes int resId, @NonNull @StyleableRes int[] attrs)1517 public TypedArray obtainStyledAttributes(@StyleRes int resId, 1518 @NonNull @StyleableRes int[] attrs) 1519 throws NotFoundException { 1520 return mThemeImpl.obtainStyledAttributes(this, null, attrs, 0, resId); 1521 } 1522 1523 /** 1524 * Return a TypedArray holding the attribute values in 1525 * <var>set</var> 1526 * that are listed in <var>attrs</var>. In addition, if the given 1527 * AttributeSet specifies a style class (through the "style" attribute), 1528 * that style will be applied on top of the base attributes it defines. 1529 * 1530 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1531 * with the array. 1532 * 1533 * <p>When determining the final value of a particular attribute, there 1534 * are four inputs that come into play:</p> 1535 * 1536 * <ol> 1537 * <li> Any attribute values in the given AttributeSet. 1538 * <li> The style resource specified in the AttributeSet (named 1539 * "style"). 1540 * <li> The default style specified by <var>defStyleAttr</var> and 1541 * <var>defStyleRes</var> 1542 * <li> The base values in this theme. 1543 * </ol> 1544 * 1545 * <p>Each of these inputs is considered in-order, with the first listed 1546 * taking precedence over the following ones. In other words, if in the 1547 * AttributeSet you have supplied <code><Button 1548 * textColor="#ff000000"></code>, then the button's text will 1549 * <em>always</em> be black, regardless of what is specified in any of 1550 * the styles. 1551 * 1552 * @param set The base set of attribute values. May be null. 1553 * @param attrs The desired attributes to be retrieved. These attribute IDs must be sorted 1554 * in ascending order. 1555 * @param defStyleAttr An attribute in the current theme that contains a 1556 * reference to a style resource that supplies 1557 * defaults values for the TypedArray. Can be 1558 * 0 to not look for defaults. 1559 * @param defStyleRes A resource identifier of a style resource that 1560 * supplies default values for the TypedArray, 1561 * used only if defStyleAttr is 0 or can not be found 1562 * in the theme. Can be 0 to not look for defaults. 1563 * 1564 * @return Returns a TypedArray holding an array of the attribute values. 1565 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1566 * when done with it. 1567 * 1568 * @see Resources#obtainAttributes 1569 * @see #obtainStyledAttributes(int[]) 1570 * @see #obtainStyledAttributes(int, int[]) 1571 */ 1572 @NonNull obtainStyledAttributes(@ullable AttributeSet set, @NonNull @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes)1573 public TypedArray obtainStyledAttributes(@Nullable AttributeSet set, 1574 @NonNull @StyleableRes int[] attrs, @AttrRes int defStyleAttr, 1575 @StyleRes int defStyleRes) { 1576 return mThemeImpl.obtainStyledAttributes(this, set, attrs, defStyleAttr, defStyleRes); 1577 } 1578 1579 /** 1580 * Retrieve the values for a set of attributes in the Theme. The 1581 * contents of the typed array are ultimately filled in by 1582 * {@link Resources#getValue}. 1583 * 1584 * @param values The base set of attribute values, must be equal in 1585 * length to {@code attrs}. All values must be of type 1586 * {@link TypedValue#TYPE_ATTRIBUTE}. 1587 * @param attrs The desired attributes to be retrieved. These attribute IDs must be sorted 1588 * in ascending order. 1589 * @return Returns a TypedArray holding an array of the attribute 1590 * values. Be sure to call {@link TypedArray#recycle()} 1591 * when done with it. 1592 * @hide 1593 */ 1594 @NonNull 1595 @UnsupportedAppUsage resolveAttributes(@onNull int[] values, @NonNull int[] attrs)1596 public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) { 1597 return mThemeImpl.resolveAttributes(this, values, attrs); 1598 } 1599 1600 /** 1601 * Retrieve the value of an attribute in the Theme. The contents of 1602 * <var>outValue</var> are ultimately filled in by 1603 * {@link Resources#getValue}. 1604 * 1605 * @param resid The resource identifier of the desired theme 1606 * attribute. 1607 * @param outValue Filled in with the ultimate resource value supplied 1608 * by the attribute. 1609 * @param resolveRefs If true, resource references will be walked; if 1610 * false, <var>outValue</var> may be a 1611 * TYPE_REFERENCE. In either case, it will never 1612 * be a TYPE_ATTRIBUTE. 1613 * 1614 * @return boolean Returns true if the attribute was found and 1615 * <var>outValue</var> is valid, else false. 1616 */ resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs)1617 public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) { 1618 return mThemeImpl.resolveAttribute(resid, outValue, resolveRefs); 1619 } 1620 1621 /** 1622 * Gets all of the attribute ids associated with this {@link Theme}. For debugging only. 1623 * 1624 * @return The int array containing attribute ids associated with this {@link Theme}. 1625 * @hide 1626 */ getAllAttributes()1627 public int[] getAllAttributes() { 1628 return mThemeImpl.getAllAttributes(); 1629 } 1630 1631 /** 1632 * Returns the resources to which this theme belongs. 1633 * 1634 * @return Resources to which this theme belongs. 1635 */ getResources()1636 public Resources getResources() { 1637 return Resources.this; 1638 } 1639 1640 /** 1641 * Return a drawable object associated with a particular resource ID 1642 * and styled for the Theme. 1643 * 1644 * @param id The desired resource identifier, as generated by the aapt 1645 * tool. This integer encodes the package, type, and resource 1646 * entry. The value 0 is an invalid identifier. 1647 * @return Drawable An object that can be used to draw this resource. 1648 * @throws NotFoundException Throws NotFoundException if the given ID 1649 * does not exist. 1650 */ getDrawable(@rawableRes int id)1651 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException { 1652 return Resources.this.getDrawable(id, this); 1653 } 1654 1655 /** 1656 * Returns a bit mask of configuration changes that will impact this 1657 * theme (and thus require completely reloading it). 1658 * 1659 * @return a bit mask of configuration changes, as defined by 1660 * {@link ActivityInfo} 1661 * @see ActivityInfo 1662 */ getChangingConfigurations()1663 public @Config int getChangingConfigurations() { 1664 return mThemeImpl.getChangingConfigurations(); 1665 } 1666 1667 /** 1668 * Print contents of this theme out to the log. For debugging only. 1669 * 1670 * @param priority The log priority to use. 1671 * @param tag The log tag to use. 1672 * @param prefix Text to prefix each line printed. 1673 */ dump(int priority, String tag, String prefix)1674 public void dump(int priority, String tag, String prefix) { 1675 mThemeImpl.dump(priority, tag, prefix); 1676 } 1677 1678 // Needed by layoutlib. getNativeTheme()1679 /*package*/ long getNativeTheme() { 1680 return mThemeImpl.getNativeTheme(); 1681 } 1682 getAppliedStyleResId()1683 /*package*/ int getAppliedStyleResId() { 1684 return mThemeImpl.getAppliedStyleResId(); 1685 } 1686 1687 /** 1688 * @hide 1689 */ getKey()1690 public ThemeKey getKey() { 1691 return mThemeImpl.getKey(); 1692 } 1693 getResourceNameFromHexString(String hexString)1694 private String getResourceNameFromHexString(String hexString) { 1695 return getResourceName(Integer.parseInt(hexString, 16)); 1696 } 1697 1698 /** 1699 * Parses {@link #getKey()} and returns a String array that holds pairs of 1700 * adjacent Theme data: resource name followed by whether or not it was 1701 * forced, as specified by {@link #applyStyle(int, boolean)}. 1702 * 1703 * @hide 1704 */ 1705 @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true) getTheme()1706 public String[] getTheme() { 1707 return mThemeImpl.getTheme(); 1708 } 1709 1710 /** @hide */ encode(@onNull ViewHierarchyEncoder encoder)1711 public void encode(@NonNull ViewHierarchyEncoder encoder) { 1712 encoder.beginObject(this); 1713 final String[] properties = getTheme(); 1714 for (int i = 0; i < properties.length; i += 2) { 1715 encoder.addProperty(properties[i], properties[i+1]); 1716 } 1717 encoder.endObject(); 1718 } 1719 1720 /** 1721 * Rebases the theme against the parent Resource object's current 1722 * configuration by re-applying the styles passed to 1723 * {@link #applyStyle(int, boolean)}. 1724 */ rebase()1725 public void rebase() { 1726 mThemeImpl.rebase(); 1727 } 1728 1729 /** 1730 * Returns the resource ID for the style specified using {@code style="..."} in the 1731 * {@link AttributeSet}'s backing XML element or {@link Resources#ID_NULL} otherwise if not 1732 * specified or otherwise not applicable. 1733 * <p> 1734 * Each {@link android.view.View} can have an explicit style specified in the layout file. 1735 * This style is used first during the {@link android.view.View} attribute resolution, then 1736 * if an attribute is not defined there the resource system looks at default style and theme 1737 * as fallbacks. 1738 * 1739 * @param set The base set of attribute values. 1740 * 1741 * @return The resource ID for the style specified using {@code style="..."} in the 1742 * {@link AttributeSet}'s backing XML element or {@link Resources#ID_NULL} otherwise 1743 * if not specified or otherwise not applicable. 1744 */ 1745 @StyleRes getExplicitStyle(@ullable AttributeSet set)1746 public int getExplicitStyle(@Nullable AttributeSet set) { 1747 if (set == null) { 1748 return ID_NULL; 1749 } 1750 int styleAttr = set.getStyleAttribute(); 1751 if (styleAttr == ID_NULL) { 1752 return ID_NULL; 1753 } 1754 String styleAttrType = getResources().getResourceTypeName(styleAttr); 1755 if ("attr".equals(styleAttrType)) { 1756 TypedValue explicitStyle = new TypedValue(); 1757 boolean resolved = resolveAttribute(styleAttr, explicitStyle, true); 1758 if (resolved) { 1759 return explicitStyle.resourceId; 1760 } 1761 } else if ("style".equals(styleAttrType)) { 1762 return styleAttr; 1763 } 1764 return ID_NULL; 1765 } 1766 1767 /** 1768 * Returns the ordered list of resource ID that are considered when resolving attribute 1769 * values when making an equivalent call to 1770 * {@link #obtainStyledAttributes(AttributeSet, int[], int, int)} . The list will include 1771 * a set of explicit styles ({@code explicitStyleRes} and it will include the default styles 1772 * ({@code defStyleAttr} and {@code defStyleRes}). 1773 * 1774 * @param defStyleAttr An attribute in the current theme that contains a 1775 * reference to a style resource that supplies 1776 * defaults values for the TypedArray. Can be 1777 * 0 to not look for defaults. 1778 * @param defStyleRes A resource identifier of a style resource that 1779 * supplies default values for the TypedArray, 1780 * used only if defStyleAttr is 0 or can not be found 1781 * in the theme. Can be 0 to not look for defaults. 1782 * @param explicitStyleRes A resource identifier of an explicit style resource. 1783 * @return ordered list of resource ID that are considered when resolving attribute values. 1784 */ 1785 @NonNull getAttributeResolutionStack(@ttrRes int defStyleAttr, @StyleRes int defStyleRes, @StyleRes int explicitStyleRes)1786 public int[] getAttributeResolutionStack(@AttrRes int defStyleAttr, 1787 @StyleRes int defStyleRes, @StyleRes int explicitStyleRes) { 1788 int[] stack = mThemeImpl.getAttributeResolutionStack( 1789 defStyleAttr, defStyleRes, explicitStyleRes); 1790 if (stack == null) { 1791 return new int[0]; 1792 } else { 1793 return stack; 1794 } 1795 } 1796 } 1797 1798 static class ThemeKey implements Cloneable { 1799 int[] mResId; 1800 boolean[] mForce; 1801 int mCount; 1802 1803 private int mHashCode = 0; 1804 append(int resId, boolean force)1805 public void append(int resId, boolean force) { 1806 if (mResId == null) { 1807 mResId = new int[4]; 1808 } 1809 1810 if (mForce == null) { 1811 mForce = new boolean[4]; 1812 } 1813 1814 mResId = GrowingArrayUtils.append(mResId, mCount, resId); 1815 mForce = GrowingArrayUtils.append(mForce, mCount, force); 1816 mCount++; 1817 1818 mHashCode = 31 * (31 * mHashCode + resId) + (force ? 1 : 0); 1819 } 1820 1821 /** 1822 * Sets up this key as a deep copy of another key. 1823 * 1824 * @param other the key to deep copy into this key 1825 */ setTo(ThemeKey other)1826 public void setTo(ThemeKey other) { 1827 mResId = other.mResId == null ? null : other.mResId.clone(); 1828 mForce = other.mForce == null ? null : other.mForce.clone(); 1829 mCount = other.mCount; 1830 } 1831 1832 @Override hashCode()1833 public int hashCode() { 1834 return mHashCode; 1835 } 1836 1837 @Override equals(Object o)1838 public boolean equals(Object o) { 1839 if (this == o) { 1840 return true; 1841 } 1842 1843 if (o == null || getClass() != o.getClass() || hashCode() != o.hashCode()) { 1844 return false; 1845 } 1846 1847 final ThemeKey t = (ThemeKey) o; 1848 if (mCount != t.mCount) { 1849 return false; 1850 } 1851 1852 final int N = mCount; 1853 for (int i = 0; i < N; i++) { 1854 if (mResId[i] != t.mResId[i] || mForce[i] != t.mForce[i]) { 1855 return false; 1856 } 1857 } 1858 1859 return true; 1860 } 1861 1862 /** 1863 * @return a shallow copy of this key 1864 */ 1865 @Override clone()1866 public ThemeKey clone() { 1867 final ThemeKey other = new ThemeKey(); 1868 other.mResId = mResId; 1869 other.mForce = mForce; 1870 other.mCount = mCount; 1871 other.mHashCode = mHashCode; 1872 return other; 1873 } 1874 } 1875 1876 /** 1877 * Generate a new Theme object for this set of Resources. It initially 1878 * starts out empty. 1879 * 1880 * @return Theme The newly created Theme container. 1881 */ newTheme()1882 public final Theme newTheme() { 1883 Theme theme = new Theme(); 1884 theme.setImpl(mResourcesImpl.newThemeImpl()); 1885 synchronized (mThemeRefs) { 1886 mThemeRefs.add(new WeakReference<>(theme)); 1887 1888 // Clean up references to garbage collected themes 1889 if (mThemeRefs.size() > mThemeRefsNextFlushSize) { 1890 mThemeRefs.removeIf(ref -> ref.get() == null); 1891 mThemeRefsNextFlushSize = Math.max(MIN_THEME_REFS_FLUSH_SIZE, 1892 2 * mThemeRefs.size()); 1893 } 1894 } 1895 return theme; 1896 } 1897 1898 /** 1899 * Retrieve a set of basic attribute values from an AttributeSet, not 1900 * performing styling of them using a theme and/or style resources. 1901 * 1902 * @param set The current attribute values to retrieve. 1903 * @param attrs The specific attributes to be retrieved. These attribute IDs must be sorted in 1904 * ascending order. 1905 * @return Returns a TypedArray holding an array of the attribute values. 1906 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1907 * when done with it. 1908 * 1909 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int) 1910 */ obtainAttributes(AttributeSet set, @StyleableRes int[] attrs)1911 public TypedArray obtainAttributes(AttributeSet set, @StyleableRes int[] attrs) { 1912 int len = attrs.length; 1913 TypedArray array = TypedArray.obtain(this, len); 1914 1915 // XXX note that for now we only work with compiled XML files. 1916 // To support generic XML files we will need to manually parse 1917 // out the attributes from the XML file (applying type information 1918 // contained in the resources and such). 1919 XmlBlock.Parser parser = (XmlBlock.Parser)set; 1920 mResourcesImpl.getAssets().retrieveAttributes(parser, attrs, array.mData, array.mIndices); 1921 1922 array.mXml = parser; 1923 1924 return array; 1925 } 1926 1927 /** 1928 * Store the newly updated configuration. 1929 * 1930 * @deprecated See {@link android.content.Context#createConfigurationContext(Configuration)}. 1931 */ 1932 @Deprecated updateConfiguration(Configuration config, DisplayMetrics metrics)1933 public void updateConfiguration(Configuration config, DisplayMetrics metrics) { 1934 updateConfiguration(config, metrics, null); 1935 } 1936 1937 /** 1938 * @hide 1939 */ updateConfiguration(Configuration config, DisplayMetrics metrics, CompatibilityInfo compat)1940 public void updateConfiguration(Configuration config, DisplayMetrics metrics, 1941 CompatibilityInfo compat) { 1942 mResourcesImpl.updateConfiguration(config, metrics, compat); 1943 } 1944 1945 /** 1946 * Update the system resources configuration if they have previously 1947 * been initialized. 1948 * 1949 * @hide 1950 */ 1951 @UnsupportedAppUsage updateSystemConfiguration(Configuration config, DisplayMetrics metrics, CompatibilityInfo compat)1952 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics, 1953 CompatibilityInfo compat) { 1954 if (mSystem != null) { 1955 mSystem.updateConfiguration(config, metrics, compat); 1956 //Log.i(TAG, "Updated system resources " + mSystem 1957 // + ": " + mSystem.getConfiguration()); 1958 } 1959 } 1960 1961 /** 1962 * Return the current display metrics that are in effect for this resource 1963 * object. The returned object should be treated as read-only. 1964 * 1965 * @return The resource's current display metrics. 1966 */ getDisplayMetrics()1967 public DisplayMetrics getDisplayMetrics() { 1968 return mResourcesImpl.getDisplayMetrics(); 1969 } 1970 1971 /** @hide */ 1972 @UnsupportedAppUsage getDisplayAdjustments()1973 public DisplayAdjustments getDisplayAdjustments() { 1974 return mResourcesImpl.getDisplayAdjustments(); 1975 } 1976 1977 /** 1978 * Return the current configuration that is in effect for this resource 1979 * object. The returned object should be treated as read-only. 1980 * 1981 * @return The resource's current configuration. 1982 */ getConfiguration()1983 public Configuration getConfiguration() { 1984 return mResourcesImpl.getConfiguration(); 1985 } 1986 1987 /** @hide */ getSizeConfigurations()1988 public Configuration[] getSizeConfigurations() { 1989 return mResourcesImpl.getSizeConfigurations(); 1990 } 1991 1992 /** 1993 * Return the compatibility mode information for the application. 1994 * The returned object should be treated as read-only. 1995 * 1996 * @return compatibility info. 1997 * @hide 1998 */ 1999 @UnsupportedAppUsage getCompatibilityInfo()2000 public CompatibilityInfo getCompatibilityInfo() { 2001 return mResourcesImpl.getCompatibilityInfo(); 2002 } 2003 2004 /** 2005 * This is just for testing. 2006 * @hide 2007 */ 2008 @VisibleForTesting 2009 @UnsupportedAppUsage setCompatibilityInfo(CompatibilityInfo ci)2010 public void setCompatibilityInfo(CompatibilityInfo ci) { 2011 if (ci != null) { 2012 mResourcesImpl.updateConfiguration(null, null, ci); 2013 } 2014 } 2015 2016 /** 2017 * Return a resource identifier for the given resource name. A fully 2018 * qualified resource name is of the form "package:type/entry". The first 2019 * two components (package and type) are optional if defType and 2020 * defPackage, respectively, are specified here. 2021 * 2022 * <p>Note: use of this function is discouraged. It is much more 2023 * efficient to retrieve resources by identifier than by name. 2024 * 2025 * @param name The name of the desired resource. 2026 * @param defType Optional default resource type to find, if "type/" is 2027 * not included in the name. Can be null to require an 2028 * explicit type. 2029 * @param defPackage Optional default package to find, if "package:" is 2030 * not included in the name. Can be null to require an 2031 * explicit package. 2032 * 2033 * @return int The associated resource identifier. Returns 0 if no such 2034 * resource was found. (0 is not a valid resource ID.) 2035 */ getIdentifier(String name, String defType, String defPackage)2036 public int getIdentifier(String name, String defType, String defPackage) { 2037 return mResourcesImpl.getIdentifier(name, defType, defPackage); 2038 } 2039 2040 /** 2041 * Return true if given resource identifier includes a package. 2042 * 2043 * @hide 2044 */ resourceHasPackage(@nyRes int resid)2045 public static boolean resourceHasPackage(@AnyRes int resid) { 2046 return (resid >>> 24) != 0; 2047 } 2048 2049 /** 2050 * Return the full name for a given resource identifier. This name is 2051 * a single string of the form "package:type/entry". 2052 * 2053 * @param resid The resource identifier whose name is to be retrieved. 2054 * 2055 * @return A string holding the name of the resource. 2056 * 2057 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2058 * 2059 * @see #getResourcePackageName 2060 * @see #getResourceTypeName 2061 * @see #getResourceEntryName 2062 */ getResourceName(@nyRes int resid)2063 public String getResourceName(@AnyRes int resid) throws NotFoundException { 2064 return mResourcesImpl.getResourceName(resid); 2065 } 2066 2067 /** 2068 * Return the package name for a given resource identifier. 2069 * 2070 * @param resid The resource identifier whose package name is to be 2071 * retrieved. 2072 * 2073 * @return A string holding the package name of the resource. 2074 * 2075 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2076 * 2077 * @see #getResourceName 2078 */ getResourcePackageName(@nyRes int resid)2079 public String getResourcePackageName(@AnyRes int resid) throws NotFoundException { 2080 return mResourcesImpl.getResourcePackageName(resid); 2081 } 2082 2083 /** 2084 * Return the type name for a given resource identifier. 2085 * 2086 * @param resid The resource identifier whose type name is to be 2087 * retrieved. 2088 * 2089 * @return A string holding the type name of the resource. 2090 * 2091 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2092 * 2093 * @see #getResourceName 2094 */ getResourceTypeName(@nyRes int resid)2095 public String getResourceTypeName(@AnyRes int resid) throws NotFoundException { 2096 return mResourcesImpl.getResourceTypeName(resid); 2097 } 2098 2099 /** 2100 * Return the entry name for a given resource identifier. 2101 * 2102 * @param resid The resource identifier whose entry name is to be 2103 * retrieved. 2104 * 2105 * @return A string holding the entry name of the resource. 2106 * 2107 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2108 * 2109 * @see #getResourceName 2110 */ getResourceEntryName(@nyRes int resid)2111 public String getResourceEntryName(@AnyRes int resid) throws NotFoundException { 2112 return mResourcesImpl.getResourceEntryName(resid); 2113 } 2114 2115 /** 2116 * Return formatted log of the last retrieved resource's resolution path. 2117 * 2118 * @return A string holding a formatted log of the steps taken to resolve the last resource. 2119 * 2120 * @throws NotFoundException Throws NotFoundException if there hasn't been a resource 2121 * resolved yet. 2122 * 2123 * @hide 2124 */ getLastResourceResolution()2125 public String getLastResourceResolution() throws NotFoundException { 2126 return mResourcesImpl.getLastResourceResolution(); 2127 } 2128 2129 /** 2130 * Parse a series of {@link android.R.styleable#Extra <extra>} tags from 2131 * an XML file. You call this when you are at the parent tag of the 2132 * extra tags, and it will return once all of the child tags have been parsed. 2133 * This will call {@link #parseBundleExtra} for each extra tag encountered. 2134 * 2135 * @param parser The parser from which to retrieve the extras. 2136 * @param outBundle A Bundle in which to place all parsed extras. 2137 * @throws XmlPullParserException 2138 * @throws IOException 2139 */ parseBundleExtras(XmlResourceParser parser, Bundle outBundle)2140 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle) 2141 throws XmlPullParserException, IOException { 2142 int outerDepth = parser.getDepth(); 2143 int type; 2144 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2145 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2146 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2147 continue; 2148 } 2149 2150 String nodeName = parser.getName(); 2151 if (nodeName.equals("extra")) { 2152 parseBundleExtra("extra", parser, outBundle); 2153 XmlUtils.skipCurrentTag(parser); 2154 2155 } else { 2156 XmlUtils.skipCurrentTag(parser); 2157 } 2158 } 2159 } 2160 2161 /** 2162 * Parse a name/value pair out of an XML tag holding that data. The 2163 * AttributeSet must be holding the data defined by 2164 * {@link android.R.styleable#Extra}. The following value types are supported: 2165 * <ul> 2166 * <li> {@link TypedValue#TYPE_STRING}: 2167 * {@link Bundle#putCharSequence Bundle.putCharSequence()} 2168 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}: 2169 * {@link Bundle#putCharSequence Bundle.putBoolean()} 2170 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}: 2171 * {@link Bundle#putCharSequence Bundle.putBoolean()} 2172 * <li> {@link TypedValue#TYPE_FLOAT}: 2173 * {@link Bundle#putCharSequence Bundle.putFloat()} 2174 * </ul> 2175 * 2176 * @param tagName The name of the tag these attributes come from; this is 2177 * only used for reporting error messages. 2178 * @param attrs The attributes from which to retrieve the name/value pair. 2179 * @param outBundle The Bundle in which to place the parsed value. 2180 * @throws XmlPullParserException If the attributes are not valid. 2181 */ parseBundleExtra(String tagName, AttributeSet attrs, Bundle outBundle)2182 public void parseBundleExtra(String tagName, AttributeSet attrs, 2183 Bundle outBundle) throws XmlPullParserException { 2184 TypedArray sa = obtainAttributes(attrs, 2185 com.android.internal.R.styleable.Extra); 2186 2187 String name = sa.getString( 2188 com.android.internal.R.styleable.Extra_name); 2189 if (name == null) { 2190 sa.recycle(); 2191 throw new XmlPullParserException("<" + tagName 2192 + "> requires an android:name attribute at " 2193 + attrs.getPositionDescription()); 2194 } 2195 2196 TypedValue v = sa.peekValue( 2197 com.android.internal.R.styleable.Extra_value); 2198 if (v != null) { 2199 if (v.type == TypedValue.TYPE_STRING) { 2200 CharSequence cs = v.coerceToString(); 2201 outBundle.putCharSequence(name, cs); 2202 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) { 2203 outBundle.putBoolean(name, v.data != 0); 2204 } else if (v.type >= TypedValue.TYPE_FIRST_INT 2205 && v.type <= TypedValue.TYPE_LAST_INT) { 2206 outBundle.putInt(name, v.data); 2207 } else if (v.type == TypedValue.TYPE_FLOAT) { 2208 outBundle.putFloat(name, v.getFloat()); 2209 } else { 2210 sa.recycle(); 2211 throw new XmlPullParserException("<" + tagName 2212 + "> only supports string, integer, float, color, and boolean at " 2213 + attrs.getPositionDescription()); 2214 } 2215 } else { 2216 sa.recycle(); 2217 throw new XmlPullParserException("<" + tagName 2218 + "> requires an android:value or android:resource attribute at " 2219 + attrs.getPositionDescription()); 2220 } 2221 2222 sa.recycle(); 2223 } 2224 2225 /** 2226 * Retrieve underlying AssetManager storage for these resources. 2227 */ getAssets()2228 public final AssetManager getAssets() { 2229 return mResourcesImpl.getAssets(); 2230 } 2231 2232 /** 2233 * Call this to remove all cached loaded layout resources from the 2234 * Resources object. Only intended for use with performance testing 2235 * tools. 2236 */ flushLayoutCache()2237 public final void flushLayoutCache() { 2238 mResourcesImpl.flushLayoutCache(); 2239 } 2240 2241 /** 2242 * Start preloading of resource data using this Resources object. Only 2243 * for use by the zygote process for loading common system resources. 2244 * {@hide} 2245 */ startPreloading()2246 public final void startPreloading() { 2247 mResourcesImpl.startPreloading(); 2248 } 2249 2250 /** 2251 * Called by zygote when it is done preloading resources, to change back 2252 * to normal Resources operation. 2253 */ finishPreloading()2254 public final void finishPreloading() { 2255 mResourcesImpl.finishPreloading(); 2256 } 2257 2258 /** 2259 * @hide 2260 */ 2261 @UnsupportedAppUsage getPreloadedDrawables()2262 public LongSparseArray<ConstantState> getPreloadedDrawables() { 2263 return mResourcesImpl.getPreloadedDrawables(); 2264 } 2265 2266 /** 2267 * Loads an XML parser for the specified file. 2268 * 2269 * @param id the resource identifier for the file 2270 * @param type the type of resource (used for logging) 2271 * @return a parser for the specified XML file 2272 * @throws NotFoundException if the file could not be loaded 2273 */ 2274 @NonNull 2275 @UnsupportedAppUsage loadXmlResourceParser(@nyRes int id, @NonNull String type)2276 XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type) 2277 throws NotFoundException { 2278 final TypedValue value = obtainTempTypedValue(); 2279 try { 2280 final ResourcesImpl impl = mResourcesImpl; 2281 impl.getValue(id, value, true); 2282 if (value.type == TypedValue.TYPE_STRING) { 2283 return impl.loadXmlResourceParser(value.string.toString(), id, 2284 value.assetCookie, type); 2285 } 2286 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) 2287 + " type #0x" + Integer.toHexString(value.type) + " is not valid"); 2288 } finally { 2289 releaseTempTypedValue(value); 2290 } 2291 } 2292 2293 /** 2294 * Loads an XML parser for the specified file. 2295 * 2296 * @param file the path for the XML file to parse 2297 * @param id the resource identifier for the file 2298 * @param assetCookie the asset cookie for the file 2299 * @param type the type of resource (used for logging) 2300 * @return a parser for the specified XML file 2301 * @throws NotFoundException if the file could not be loaded 2302 */ 2303 @NonNull 2304 @UnsupportedAppUsage loadXmlResourceParser(String file, int id, int assetCookie, String type)2305 XmlResourceParser loadXmlResourceParser(String file, int id, int assetCookie, 2306 String type) throws NotFoundException { 2307 return mResourcesImpl.loadXmlResourceParser(file, id, assetCookie, type); 2308 } 2309 2310 /** 2311 * Called by ConfigurationBoundResourceCacheTest. 2312 * @hide 2313 */ 2314 @VisibleForTesting calcConfigChanges(Configuration config)2315 public int calcConfigChanges(Configuration config) { 2316 return mResourcesImpl.calcConfigChanges(config); 2317 } 2318 2319 /** 2320 * Obtains styled attributes from the theme, if available, or unstyled 2321 * resources if the theme is null. 2322 * 2323 * @hide 2324 */ obtainAttributes( Resources res, Theme theme, AttributeSet set, int[] attrs)2325 public static TypedArray obtainAttributes( 2326 Resources res, Theme theme, AttributeSet set, int[] attrs) { 2327 if (theme == null) { 2328 return res.obtainAttributes(set, attrs); 2329 } 2330 return theme.obtainStyledAttributes(set, attrs, 0, 0); 2331 } 2332 } 2333