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