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