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