blob: 7ce3721e81bc7b42a1a483b7cc3336f4075a7dcf [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Tor Norbye80756e32015-03-02 09:39:27 -080019import android.annotation.ColorInt;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080020import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021
22import org.xmlpull.v1.XmlPullParser;
23import org.xmlpull.v1.XmlPullParserException;
24
Alan Viverette45c4bbb2015-01-05 14:59:19 -080025import android.animation.Animator;
26import android.animation.StateListAnimator;
Tor Norbye7b9c9122013-05-30 16:48:33 -070027import android.annotation.AnimRes;
28import android.annotation.AnyRes;
29import android.annotation.ArrayRes;
30import android.annotation.BoolRes;
31import android.annotation.ColorRes;
32import android.annotation.DimenRes;
33import android.annotation.DrawableRes;
34import android.annotation.FractionRes;
35import android.annotation.IntegerRes;
36import android.annotation.LayoutRes;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080037import android.annotation.NonNull;
Alan Viverette3b5c4272014-05-20 13:20:42 -070038import android.annotation.Nullable;
Tor Norbye7b9c9122013-05-30 16:48:33 -070039import android.annotation.PluralsRes;
40import android.annotation.RawRes;
41import android.annotation.StringRes;
42import android.annotation.XmlRes;
Dianne Hackbornebff8f92011-05-12 18:07:47 -070043import android.content.pm.ActivityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.graphics.Movie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.graphics.drawable.ColorDrawable;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080046import android.graphics.drawable.Drawable;
Masanori Oginoc7d9d272010-07-10 12:10:41 +090047import android.graphics.drawable.Drawable.ConstantState;
Dianne Hackborn3b3e1452009-09-24 19:22:12 -070048import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Bundle;
Romain Guy3b748a42013-04-17 18:54:38 -070050import android.os.Trace;
Alan Viverette75257ce2014-05-22 19:31:38 -070051import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.util.AttributeSet;
53import android.util.DisplayMetrics;
54import android.util.Log;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080055import android.util.LongSparseArray;
56import android.util.Pools.SynchronizedPool;
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070057import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.util.TypedValue;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080059import android.view.ViewDebug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
61import java.io.IOException;
62import java.io.InputStream;
63import java.lang.ref.WeakReference;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080064import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Elliott Hughes1ad636c2010-07-01 16:51:48 -070066import libcore.icu.NativePluralRules;
67
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068/**
69 * Class for accessing an application's resources. This sits on top of the
Scott Mainf4f05b82011-01-07 14:38:23 -080070 * asset manager of the application (accessible through {@link #getAssets}) and
71 * provides a high-level API for getting typed data from the assets.
72 *
73 * <p>The Android resource system keeps track of all non-code assets associated with an
74 * application. You can use this class to access your application's resources. You can generally
75 * acquire the {@link android.content.res.Resources} instance associated with your application
76 * with {@link android.content.Context#getResources getResources()}.</p>
77 *
78 * <p>The Android SDK tools compile your application's resources into the application binary
79 * at build time. To use a resource, you must install it correctly in the source tree (inside
80 * your project's {@code res/} directory) and build your application. As part of the build
81 * process, the SDK tools generate symbols for each resource, which you can use in your application
82 * code to access the resources.</p>
83 *
84 * <p>Using application resources makes it easy to update various characteristics of your
85 * application without modifying code, and&mdash;by providing sets of alternative
86 * resources&mdash;enables you to optimize your application for a variety of device configurations
87 * (such as for different languages and screen sizes). This is an important aspect of developing
88 * Android applications that are compatible on different types of devices.</p>
89 *
90 * <p>For more information about using resources, see the documentation about <a
91 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 */
93public class Resources {
94 static final String TAG = "Resources";
Alan Viverette562a6a82014-01-31 11:07:29 -080095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private static final boolean DEBUG_LOAD = false;
97 private static final boolean DEBUG_CONFIG = false;
98 private static final boolean TRACE_FOR_PRELOAD = false;
Dianne Hackborn9b44aae2011-09-02 19:17:16 -070099 private static final boolean TRACE_FOR_MISS_PRELOAD = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Alan Viverette562a6a82014-01-31 11:07:29 -0800101 private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
102 ActivityInfo.CONFIG_LAYOUT_DIRECTION);
103
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700104 private static final int ID_OTHER = 0x01000004;
105
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800106 private static final Object sSync = new Object();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 // Information about preloaded resources. Note that they are not
109 // protected by a lock, because while preloading in zygote we are all
110 // single-threaded, and after that these are immutable.
Alan Viverette52b999f2014-03-24 18:00:26 -0700111 private static final LongSparseArray<ConstantState>[] sPreloadedDrawables;
112 private static final LongSparseArray<ConstantState> sPreloadedColorDrawables
Alan Viverettea8636c92015-03-27 10:44:39 -0700113 = new LongSparseArray<>();
Alan Viverettee0f95f32015-04-01 13:10:18 -0700114 private static final LongSparseArray<android.content.res.ConstantState<ColorStateList>>
115 sPreloadedColorStateLists = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700116
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700117 // Pool of TypedArrays targeted to this Resources object.
Alan Viverettea8636c92015-03-27 10:44:39 -0700118 final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700119
Alan Viveretteedc46642014-02-01 01:43:16 -0800120 // Used by BridgeResources in layoutlib
121 static Resources mSystem = null;
122
Dianne Hackborndde331c2012-08-03 14:01:57 -0700123 private static boolean sPreloaded;
124 private static int sPreloadedDensity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800126 // These are protected by mAccessLock.
Alan Viverette562a6a82014-01-31 11:07:29 -0800127 private final Object mAccessLock = new Object();
128 private final Configuration mTmpConfig = new Configuration();
Alan Viverette75257ce2014-05-22 19:31:38 -0700129 private final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> mDrawableCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700130 new ArrayMap<>();
Alan Viverette75257ce2014-05-22 19:31:38 -0700131 private final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> mColorDrawableCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700132 new ArrayMap<>();
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800133 private final ConfigurationBoundResourceCache<ColorStateList> mColorStateListCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700134 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700135 private final ConfigurationBoundResourceCache<Animator> mAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700136 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700137 private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700138 new ConfigurationBoundResourceCache<>(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Alan Viverette562a6a82014-01-31 11:07:29 -0800140 private TypedValue mTmpValue = new TypedValue();
141 private boolean mPreloading;
142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 private int mLastCachedXmlBlockIndex = -1;
144 private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 };
145 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4];
146
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700147 final AssetManager mAssets;
148 final DisplayMetrics mMetrics = new DisplayMetrics();
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private final Configuration mConfiguration = new Configuration();
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700151 private NativePluralRules mPluralRule;
Craig Mautner48d0d182013-06-11 07:53:06 -0700152
153 private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
Alan Viverette52b999f2014-03-24 18:00:26 -0700154
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700155 static {
156 sPreloadedDrawables = new LongSparseArray[2];
Alan Viverettea8636c92015-03-27 10:44:39 -0700157 sPreloadedDrawables[0] = new LongSparseArray<>();
158 sPreloadedDrawables[1] = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700159 }
160
Alan Viverette62599332014-04-01 14:57:39 -0700161 /**
162 * Returns the most appropriate default theme for the specified target SDK version.
Alan Viverette5effd7e2014-05-05 12:25:33 -0700163 * <ul>
164 * <li>Below API 11: Gingerbread
165 * <li>APIs 11 thru 14: Holo
166 * <li>APIs 14 thru XX: Device default dark
167 * <li>API XX and above: Device default light with dark action bar
168 * </ul>
Alan Viverette62599332014-04-01 14:57:39 -0700169 *
170 * @param curTheme The current theme, or 0 if not specified.
171 * @param targetSdkVersion The target SDK version.
172 * @return A theme resource identifier
173 * @hide
174 */
Alan Viverette5effd7e2014-05-05 12:25:33 -0700175 public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800176 return selectSystemTheme(curTheme, targetSdkVersion,
Alan Viverette5effd7e2014-05-05 12:25:33 -0700177 com.android.internal.R.style.Theme,
178 com.android.internal.R.style.Theme_Holo,
179 com.android.internal.R.style.Theme_DeviceDefault,
180 com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar);
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800181 }
Alan Viverette62599332014-04-01 14:57:39 -0700182
Alan Viverette5effd7e2014-05-05 12:25:33 -0700183 /** @hide */
184 public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo,
185 int dark, int deviceDefault) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800186 if (curTheme != 0) {
187 return curTheme;
188 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700189 if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) {
190 return orig;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800191 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700192 if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
193 return holo;
194 }
195 if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) {
196 return dark;
197 }
198 return deviceDefault;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800199 }
Alan Viverette62599332014-04-01 14:57:39 -0700200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 /**
Yigit Boyard422dc32014-09-25 12:23:35 -0700202 * Used by AnimatorInflater.
203 *
204 * @hide
205 */
206 public ConfigurationBoundResourceCache<Animator> getAnimatorCache() {
207 return mAnimatorCache;
208 }
209
210 /**
211 * Used by AnimatorInflater.
212 *
213 * @hide
214 */
215 public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
216 return mStateListAnimatorCache;
217 }
218
219 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 * This exception is thrown by the resource APIs when a requested resource
221 * can not be found.
222 */
223 public static class NotFoundException extends RuntimeException {
224 public NotFoundException() {
225 }
226
227 public NotFoundException(String name) {
228 super(name);
229 }
230 }
231
232 /**
233 * Create a new Resources object on top of an existing set of assets in an
234 * AssetManager.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800235 *
236 * @param assets Previously created AssetManager.
237 * @param metrics Current display metrics to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800239 * @param config Desired device configuration to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 * selecting/computing resource values (optional).
241 */
Romain Guy5d911c32012-04-12 16:25:17 -0700242 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
Wale Ogunwale60454db2015-01-23 16:05:07 -0800243 this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700244 }
245
246 /**
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700247 * Creates a new Resources object with CompatibilityInfo.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800248 *
249 * @param assets Previously created AssetManager.
250 * @param metrics Current display metrics to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700251 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800252 * @param config Desired device configuration to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700253 * selecting/computing resource values (optional).
Craig Mautner48d0d182013-06-11 07:53:06 -0700254 * @param compatInfo this resource's compatibility info. Must not be null.
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700255 * @hide
256 */
Craig Mautner48d0d182013-06-11 07:53:06 -0700257 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
Wale Ogunwale60454db2015-01-23 16:05:07 -0800258 CompatibilityInfo compatInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mAssets = assets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 mMetrics.setToDefaults();
Adam Lesinski79a8ffe2013-09-19 20:33:15 -0700261 if (compatInfo != null) {
262 mCompatibilityInfo = compatInfo;
263 }
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700264 updateConfiguration(config, metrics);
265 assets.ensureStringBlocks();
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700266 }
267
268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 * Return a global shared Resources object that provides access to only
Wale Ogunwale60454db2015-01-23 16:05:07 -0800270 * system resources (no application resources), and is not configured for
271 * the current screen (can not use dimension units, does not change based
272 * on orientation, etc).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 */
274 public static Resources getSystem() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800275 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 Resources ret = mSystem;
277 if (ret == null) {
278 ret = new Resources();
279 mSystem = ret;
280 }
281
282 return ret;
283 }
284 }
285
286 /**
287 * Return the string value associated with a particular resource ID. The
288 * returned object will be a String if this is a plain string; it will be
289 * some other type of CharSequence if it is styled.
290 * {@more}
291 *
292 * @param id The desired resource identifier, as generated by the aapt
293 * tool. This integer encodes the package, type, and resource
294 * entry. The value 0 is an invalid identifier.
295 *
296 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
297 *
298 * @return CharSequence The string data associated with the resource, plus
299 * possibly styled text information.
300 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700301 public CharSequence getText(@StringRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 CharSequence res = mAssets.getResourceText(id);
303 if (res != null) {
304 return res;
305 }
306 throw new NotFoundException("String resource ID #0x"
307 + Integer.toHexString(id));
308 }
309
310 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800311 * Returns the character sequence necessary for grammatically correct pluralization
312 * of the given resource ID for the given quantity.
313 * Note that the character sequence is selected based solely on grammatical necessity,
314 * and that such rules differ between languages. Do not assume you know which string
315 * will be returned for a given quantity. See
316 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
317 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700318 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * @param id The desired resource identifier, as generated by the aapt
320 * tool. This integer encodes the package, type, and resource
321 * entry. The value 0 is an invalid identifier.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700322 * @param quantity The number used to get the correct string for the current language's
323 * plural rules.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 *
325 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
326 *
327 * @return CharSequence The string data associated with the resource, plus
328 * possibly styled text information.
329 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700330 public CharSequence getQuantityText(@PluralsRes int id, int quantity)
331 throws NotFoundException {
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700332 NativePluralRules rule = getPluralRule();
333 CharSequence res = mAssets.getResourceBagText(id,
334 attrForQuantityCode(rule.quantityForInt(quantity)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 if (res != null) {
336 return res;
337 }
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700338 res = mAssets.getResourceBagText(id, ID_OTHER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 if (res != null) {
340 return res;
341 }
342 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
343 + " quantity=" + quantity
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700344 + " item=" + stringForQuantityCode(rule.quantityForInt(quantity)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700347 private NativePluralRules getPluralRule() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800348 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 if (mPluralRule == null) {
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700350 mPluralRule = NativePluralRules.forLocale(mConfiguration.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 }
352 return mPluralRule;
353 }
354 }
355
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700356 private static int attrForQuantityCode(int quantityCode) {
357 switch (quantityCode) {
358 case NativePluralRules.ZERO: return 0x01000005;
359 case NativePluralRules.ONE: return 0x01000006;
360 case NativePluralRules.TWO: return 0x01000007;
361 case NativePluralRules.FEW: return 0x01000008;
362 case NativePluralRules.MANY: return 0x01000009;
363 default: return ID_OTHER;
364 }
365 }
366
367 private static String stringForQuantityCode(int quantityCode) {
368 switch (quantityCode) {
369 case NativePluralRules.ZERO: return "zero";
370 case NativePluralRules.ONE: return "one";
371 case NativePluralRules.TWO: return "two";
372 case NativePluralRules.FEW: return "few";
373 case NativePluralRules.MANY: return "many";
374 default: return "other";
375 }
376 }
377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 /**
379 * Return the string value associated with a particular resource ID. It
380 * will be stripped of any styled text information.
381 * {@more}
382 *
383 * @param id The desired resource identifier, as generated by the aapt
384 * tool. This integer encodes the package, type, and resource
385 * entry. The value 0 is an invalid identifier.
386 *
387 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
388 *
389 * @return String The string data associated with the resource,
390 * stripped of styled text information.
391 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700392 public String getString(@StringRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 CharSequence res = getText(id);
394 if (res != null) {
395 return res.toString();
396 }
397 throw new NotFoundException("String resource ID #0x"
398 + Integer.toHexString(id));
399 }
400
401
402 /**
403 * Return the string value associated with a particular resource ID,
404 * substituting the format arguments as defined in {@link java.util.Formatter}
405 * and {@link java.lang.String#format}. It will be stripped of any styled text
406 * information.
407 * {@more}
408 *
409 * @param id The desired resource identifier, as generated by the aapt
410 * tool. This integer encodes the package, type, and resource
411 * entry. The value 0 is an invalid identifier.
412 *
413 * @param formatArgs The format arguments that will be used for substitution.
414 *
415 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
416 *
417 * @return String The string data associated with the resource,
418 * stripped of styled text information.
419 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700420 public String getString(@StringRes int id, Object... formatArgs)
421 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 String raw = getString(id);
423 return String.format(mConfiguration.locale, raw, formatArgs);
424 }
425
426 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800427 * Formats the string necessary for grammatically correct pluralization
428 * of the given resource ID for the given quantity, using the given arguments.
429 * Note that the string is selected based solely on grammatical necessity,
430 * and that such rules differ between languages. Do not assume you know which string
431 * will be returned for a given quantity. See
432 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
433 * for more detail.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 *
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800435 * <p>Substitution of format arguments works as if using
436 * {@link java.util.Formatter} and {@link java.lang.String#format}.
437 * The resulting string will be stripped of any styled text information.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700438 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 * @param id The desired resource identifier, as generated by the aapt
440 * tool. This integer encodes the package, type, and resource
441 * entry. The value 0 is an invalid identifier.
442 * @param quantity The number used to get the correct string for the current language's
443 * plural rules.
444 * @param formatArgs The format arguments that will be used for substitution.
445 *
446 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
447 *
448 * @return String The string data associated with the resource,
449 * stripped of styled text information.
450 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700451 public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 throws NotFoundException {
453 String raw = getQuantityText(id, quantity).toString();
454 return String.format(mConfiguration.locale, raw, formatArgs);
455 }
456
457 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800458 * Returns the string necessary for grammatically correct pluralization
459 * of the given resource ID for the given quantity.
460 * Note that the string is selected based solely on grammatical necessity,
461 * and that such rules differ between languages. Do not assume you know which string
462 * will be returned for a given quantity. See
463 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
464 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700465 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 * @param id The desired resource identifier, as generated by the aapt
467 * tool. This integer encodes the package, type, and resource
468 * entry. The value 0 is an invalid identifier.
469 * @param quantity The number used to get the correct string for the current language's
470 * plural rules.
471 *
472 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
473 *
474 * @return String The string data associated with the resource,
475 * stripped of styled text information.
476 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700477 public String getQuantityString(@PluralsRes int id, int quantity)
478 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 return getQuantityText(id, quantity).toString();
480 }
481
482 /**
483 * Return the string value associated with a particular resource ID. The
484 * returned object will be a String if this is a plain string; it will be
485 * some other type of CharSequence if it is styled.
486 *
487 * @param id The desired resource identifier, as generated by the aapt
488 * tool. This integer encodes the package, type, and resource
489 * entry. The value 0 is an invalid identifier.
490 *
491 * @param def The default CharSequence to return.
492 *
493 * @return CharSequence The string data associated with the resource, plus
494 * possibly styled text information, or def if id is 0 or not found.
495 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700496 public CharSequence getText(@StringRes int id, CharSequence def) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
498 return res != null ? res : def;
499 }
500
501 /**
502 * Return the styled text array associated with a particular resource ID.
503 *
504 * @param id The desired resource identifier, as generated by the aapt
505 * tool. This integer encodes the package, type, and resource
506 * entry. The value 0 is an invalid identifier.
507 *
508 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
509 *
510 * @return The styled text array associated with the resource.
511 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700512 public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 CharSequence[] res = mAssets.getResourceTextArray(id);
514 if (res != null) {
515 return res;
516 }
517 throw new NotFoundException("Text array resource ID #0x"
518 + Integer.toHexString(id));
519 }
520
521 /**
522 * Return the string array associated with a particular resource ID.
523 *
524 * @param id The desired resource identifier, as generated by the aapt
525 * tool. This integer encodes the package, type, and resource
526 * entry. The value 0 is an invalid identifier.
527 *
528 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
529 *
530 * @return The string array associated with the resource.
531 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700532 public String[] getStringArray(@ArrayRes int id)
533 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 String[] res = mAssets.getResourceStringArray(id);
535 if (res != null) {
536 return res;
537 }
538 throw new NotFoundException("String array resource ID #0x"
539 + Integer.toHexString(id));
540 }
541
542 /**
543 * Return the int array associated with a particular resource ID.
544 *
545 * @param id The desired resource identifier, as generated by the aapt
546 * tool. This integer encodes the package, type, and resource
547 * entry. The value 0 is an invalid identifier.
548 *
549 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
550 *
551 * @return The int array associated with the resource.
552 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700553 public int[] getIntArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 int[] res = mAssets.getArrayIntResource(id);
555 if (res != null) {
556 return res;
557 }
558 throw new NotFoundException("Int array resource ID #0x"
559 + Integer.toHexString(id));
560 }
561
562 /**
563 * Return an array of heterogeneous values.
564 *
565 * @param id The desired resource identifier, as generated by the aapt
566 * tool. This integer encodes the package, type, and resource
567 * entry. The value 0 is an invalid identifier.
568 *
569 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
570 *
571 * @return Returns a TypedArray holding an array of the array values.
572 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
573 * when done with it.
574 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700575 public TypedArray obtainTypedArray(@ArrayRes int id)
576 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 int len = mAssets.getArraySize(id);
578 if (len < 0) {
579 throw new NotFoundException("Array resource ID #0x"
580 + Integer.toHexString(id));
581 }
582
Alan Viverette52b999f2014-03-24 18:00:26 -0700583 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 array.mLength = mAssets.retrieveArray(id, array.mData);
585 array.mIndices[0] = 0;
586
587 return array;
588 }
589
590 /**
591 * Retrieve a dimensional for a particular resource ID. Unit
592 * conversions are based on the current {@link DisplayMetrics} associated
593 * with the resources.
594 *
595 * @param id The desired resource identifier, as generated by the aapt
596 * tool. This integer encodes the package, type, and resource
597 * entry. The value 0 is an invalid identifier.
598 *
599 * @return Resource dimension value multiplied by the appropriate
600 * metric.
601 *
602 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
603 *
604 * @see #getDimensionPixelOffset
605 * @see #getDimensionPixelSize
606 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700607 public float getDimension(@DimenRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800608 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800610 if (value == null) {
611 mTmpValue = value = new TypedValue();
612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 getValue(id, value, true);
614 if (value.type == TypedValue.TYPE_DIMENSION) {
615 return TypedValue.complexToDimension(value.data, mMetrics);
616 }
617 throw new NotFoundException(
618 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
619 + Integer.toHexString(value.type) + " is not valid");
620 }
621 }
622
623 /**
624 * Retrieve a dimensional for a particular resource ID for use
625 * as an offset in raw pixels. This is the same as
626 * {@link #getDimension}, except the returned value is converted to
627 * integer pixels for you. An offset conversion involves simply
628 * truncating the base value to an integer.
629 *
630 * @param id The desired resource identifier, as generated by the aapt
631 * tool. This integer encodes the package, type, and resource
632 * entry. The value 0 is an invalid identifier.
633 *
634 * @return Resource dimension value multiplied by the appropriate
635 * metric and truncated to integer pixels.
636 *
637 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
638 *
639 * @see #getDimension
640 * @see #getDimensionPixelSize
641 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700642 public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800643 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800645 if (value == null) {
646 mTmpValue = value = new TypedValue();
647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 getValue(id, value, true);
649 if (value.type == TypedValue.TYPE_DIMENSION) {
650 return TypedValue.complexToDimensionPixelOffset(
651 value.data, mMetrics);
652 }
653 throw new NotFoundException(
654 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
655 + Integer.toHexString(value.type) + " is not valid");
656 }
657 }
658
659 /**
660 * Retrieve a dimensional for a particular resource ID for use
661 * as a size in raw pixels. This is the same as
662 * {@link #getDimension}, except the returned value is converted to
663 * integer pixels for use as a size. A size conversion involves
664 * rounding the base value, and ensuring that a non-zero base value
665 * is at least one pixel in size.
666 *
667 * @param id The desired resource identifier, as generated by the aapt
668 * tool. This integer encodes the package, type, and resource
669 * entry. The value 0 is an invalid identifier.
670 *
671 * @return Resource dimension value multiplied by the appropriate
672 * metric and truncated to integer pixels.
673 *
674 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
675 *
676 * @see #getDimension
677 * @see #getDimensionPixelOffset
678 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700679 public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800680 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800682 if (value == null) {
683 mTmpValue = value = new TypedValue();
684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 getValue(id, value, true);
686 if (value.type == TypedValue.TYPE_DIMENSION) {
687 return TypedValue.complexToDimensionPixelSize(
688 value.data, mMetrics);
689 }
690 throw new NotFoundException(
691 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
692 + Integer.toHexString(value.type) + " is not valid");
693 }
694 }
695
696 /**
697 * Retrieve a fractional unit for a particular resource ID.
698 *
699 * @param id The desired resource identifier, as generated by the aapt
700 * tool. This integer encodes the package, type, and resource
701 * entry. The value 0 is an invalid identifier.
702 * @param base The base value of this fraction. In other words, a
703 * standard fraction is multiplied by this value.
704 * @param pbase The parent base value of this fraction. In other
705 * words, a parent fraction (nn%p) is multiplied by this
706 * value.
707 *
708 * @return Attribute fractional value multiplied by the appropriate
709 * base value.
710 *
711 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
712 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700713 public float getFraction(@FractionRes int id, int base, int pbase) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800714 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800716 if (value == null) {
717 mTmpValue = value = new TypedValue();
718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 getValue(id, value, true);
720 if (value.type == TypedValue.TYPE_FRACTION) {
721 return TypedValue.complexToFraction(value.data, base, pbase);
722 }
723 throw new NotFoundException(
724 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
725 + Integer.toHexString(value.type) + " is not valid");
726 }
727 }
728
729 /**
730 * Return a drawable object associated with a particular resource ID.
731 * Various types of objects will be returned depending on the underlying
732 * resource -- for example, a solid color, PNG image, scalable image, etc.
733 * The Drawable API hides these implementation details.
Dianne Hackbornfb5c3db2012-05-18 15:24:24 -0700734 *
735 * <p class="note"><strong>Note:</strong> Prior to
736 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
737 * would not correctly retrieve the final configuration density when
738 * the resource ID passed here is an alias to another Drawable resource.
739 * This means that if the density configuration of the alias resource
740 * is different than the actual resource, the density of the returned
741 * Drawable would be incorrect, resulting in bad scaling. To work
742 * around this, you can instead retrieve the Drawable through
743 * {@link TypedArray#getDrawable TypedArray.getDrawable}. Use
744 * {@link android.content.Context#obtainStyledAttributes(int[])
745 * Context.obtainStyledAttributes} with
746 * an array containing the resource ID of interest to create the TypedArray.</p>
747 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700748 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
749 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
750 * or {@link #getDrawable(int, Theme)} passing the desired theme.</p>
751 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 * @param id The desired resource identifier, as generated by the aapt
753 * tool. This integer encodes the package, type, and resource
754 * entry. The value 0 is an invalid identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 * @return Drawable An object that can be used to draw this resource.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800756 * @throws NotFoundException Throws NotFoundException if the given ID does
757 * not exist.
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700758 * @see #getDrawable(int, Theme)
Alan Viverettec10e3962014-12-02 14:58:08 -0800759 * @deprecated Use {@link #getDrawable(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 */
Alan Viverettec10e3962014-12-02 14:58:08 -0800761 @Deprecated
762 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -0700763 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette34a14f962014-08-15 16:13:15 -0700764 final Drawable d = getDrawable(id, null);
Alan Viverette7e0aaae2014-11-24 11:27:09 -0800765 if (d != null && d.canApplyTheme()) {
Alan Viverette34a14f962014-08-15 16:13:15 -0700766 Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
767 + "attributes! Consider using Resources.getDrawable(int, Theme) or "
768 + "Context.getDrawable(int).", new RuntimeException());
769 }
770 return d;
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800771 }
772
773 /**
774 * Return a drawable object associated with a particular resource ID and
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700775 * styled for the specified theme. Various types of objects will be
776 * returned depending on the underlying resource -- for example, a solid
777 * color, PNG image, scalable image, etc.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800778 *
779 * @param id The desired resource identifier, as generated by the aapt
780 * tool. This integer encodes the package, type, and resource
781 * entry. The value 0 is an invalid identifier.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700782 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800783 * @return Drawable An object that can be used to draw this resource.
784 * @throws NotFoundException Throws NotFoundException if the given ID does
785 * not exist.
786 */
Alan Viverettec10e3962014-12-02 14:58:08 -0800787 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -0700788 public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800789 TypedValue value;
790 synchronized (mAccessLock) {
791 value = mTmpValue;
792 if (value == null) {
793 value = new TypedValue();
794 } else {
795 mTmpValue = null;
796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 getValue(id, value, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800799 final Drawable res = loadDrawable(value, id, theme);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800800 synchronized (mAccessLock) {
801 if (mTmpValue == null) {
802 mTmpValue = value;
803 }
804 }
805 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
807
808 /**
Kenny Root55fc8502010-10-28 14:47:01 -0700809 * Return a drawable object associated with a particular resource ID for the
810 * given screen density in DPI. This will set the drawable's density to be
811 * the device's density multiplied by the ratio of actual drawable density
812 * to requested density. This allows the drawable to be scaled up to the
813 * correct size if needed. Various types of objects will be returned
814 * depending on the underlying resource -- for example, a solid color, PNG
815 * image, scalable image, etc. The Drawable API hides these implementation
816 * details.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800817 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700818 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
819 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
820 * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired
821 * theme.</p>
822 *
Kenny Root55fc8502010-10-28 14:47:01 -0700823 * @param id The desired resource identifier, as generated by the aapt tool.
824 * This integer encodes the package, type, and resource entry.
825 * The value 0 is an invalid identifier.
826 * @param density the desired screen density indicated by the resource as
827 * found in {@link DisplayMetrics}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800828 * @return Drawable An object that can be used to draw this resource.
Kenny Root55fc8502010-10-28 14:47:01 -0700829 * @throws NotFoundException Throws NotFoundException if the given ID does
830 * not exist.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800831 * @see #getDrawableForDensity(int, int, Theme)
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800832 * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead.
Kenny Root55fc8502010-10-28 14:47:01 -0700833 */
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800834 @Deprecated
835 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -0700836 public Drawable getDrawableForDensity(@DrawableRes int id, int density) throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800837 return getDrawableForDensity(id, density, null);
838 }
839
840 /**
841 * Return a drawable object associated with a particular resource ID for the
842 * given screen density in DPI and styled for the specified theme.
843 *
844 * @param id The desired resource identifier, as generated by the aapt tool.
845 * This integer encodes the package, type, and resource entry.
846 * The value 0 is an invalid identifier.
847 * @param density The desired screen density indicated by the resource as
848 * found in {@link DisplayMetrics}.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700849 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800850 * @return Drawable An object that can be used to draw this resource.
851 * @throws NotFoundException Throws NotFoundException if the given ID does
852 * not exist.
853 */
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800854 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -0700855 public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800856 TypedValue value;
857 synchronized (mAccessLock) {
858 value = mTmpValue;
859 if (value == null) {
860 value = new TypedValue();
861 } else {
862 mTmpValue = null;
863 }
Kenny Root55fc8502010-10-28 14:47:01 -0700864 getValueForDensity(id, density, value, true);
865
866 /*
867 * Pretend the requested density is actually the display density. If
868 * the drawable returned is not the requested density, then force it
869 * to be scaled later by dividing its density by the ratio of
870 * requested density to actual device density. Drawables that have
871 * undefined density or no density don't need to be handled here.
872 */
873 if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
874 if (value.density == density) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700875 value.density = mMetrics.densityDpi;
Kenny Root55fc8502010-10-28 14:47:01 -0700876 } else {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700877 value.density = (value.density * mMetrics.densityDpi) / density;
Kenny Root55fc8502010-10-28 14:47:01 -0700878 }
879 }
Kenny Root55fc8502010-10-28 14:47:01 -0700880 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800881
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800882 final Drawable res = loadDrawable(value, id, theme);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800883 synchronized (mAccessLock) {
884 if (mTmpValue == null) {
885 mTmpValue = value;
886 }
887 }
888 return res;
Kenny Root55fc8502010-10-28 14:47:01 -0700889 }
890
891 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * Return a movie object associated with the particular resource ID.
893 * @param id The desired resource identifier, as generated by the aapt
894 * tool. This integer encodes the package, type, and resource
895 * entry. The value 0 is an invalid identifier.
896 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
897 *
898 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700899 public Movie getMovie(@RawRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 InputStream is = openRawResource(id);
901 Movie movie = Movie.decodeStream(is);
902 try {
903 is.close();
904 }
905 catch (java.io.IOException e) {
906 // don't care, since the return value is valid
907 }
908 return movie;
909 }
910
911 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800912 * Returns a color integer associated with a particular resource ID. If the
913 * resource holds a complex {@link ColorStateList}, then the default color
914 * from the set is returned.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 *
916 * @param id The desired resource identifier, as generated by the aapt
917 * tool. This integer encodes the package, type, and resource
918 * entry. The value 0 is an invalid identifier.
919 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800920 * @throws NotFoundException Throws NotFoundException if the given ID does
921 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800923 * @return A single color value in the form 0xAARRGGBB.
924 * @deprecated Use {@link #getColor(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 */
Tor Norbye80756e32015-03-02 09:39:27 -0800926 @ColorInt
Alan Viverette4a357cd2015-03-18 18:37:18 -0700927 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700928 public int getColor(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800929 return getColor(id, null);
930 }
931
932 /**
933 * Returns a themed color integer associated with a particular resource ID.
934 * If the resource holds a complex {@link ColorStateList}, then the default
935 * color from the set is returned.
936 *
937 * @param id The desired resource identifier, as generated by the aapt
938 * tool. This integer encodes the package, type, and resource
939 * entry. The value 0 is an invalid identifier.
940 * @param theme The theme used to style the color attributes, may be
941 * {@code null}.
942 *
943 * @throws NotFoundException Throws NotFoundException if the given ID does
944 * not exist.
945 *
946 * @return A single color value in the form 0xAARRGGBB.
947 */
Tor Norbye80756e32015-03-02 09:39:27 -0800948 @ColorInt
Tor Norbye7b9c9122013-05-30 16:48:33 -0700949 public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800950 TypedValue value;
951 synchronized (mAccessLock) {
952 value = mTmpValue;
953 if (value == null) {
954 value = new TypedValue();
955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 getValue(id, value, true);
957 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800958 && value.type <= TypedValue.TYPE_LAST_INT) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800959 mTmpValue = value;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 return value.data;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800961 } else if (value.type != TypedValue.TYPE_STRING) {
962 throw new NotFoundException(
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800963 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
964 + Integer.toHexString(value.type) + " is not valid");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
Dianne Hackborne5b50a62013-02-11 16:18:42 -0800966 mTmpValue = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800968
969 final ColorStateList csl = loadColorStateList(value, id, theme);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800970 synchronized (mAccessLock) {
971 if (mTmpValue == null) {
972 mTmpValue = value;
973 }
974 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800975
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800976 return csl.getDefaultColor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
978
979 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800980 * Returns a color state list associated with a particular resource ID. The
981 * resource may contain either a single raw color value or a complex
982 * {@link ColorStateList} holding multiple possible colors.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 *
984 * @param id The desired resource identifier of a {@link ColorStateList},
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800985 * as generated by the aapt tool. This integer encodes the
986 * package, type, and resource entry. The value 0 is an invalid
987 * identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800989 * @throws NotFoundException Throws NotFoundException if the given ID does
990 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800992 * @return A ColorStateList object containing either a single solid color
993 * or multiple colors that can be selected based on a state.
994 * @deprecated Use {@link #getColorStateList(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 */
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800996 @Nullable
Alan Viverette4a357cd2015-03-18 18:37:18 -0700997 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700998 public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800999 final ColorStateList csl = getColorStateList(id, null);
1000 if (csl != null && csl.canApplyTheme()) {
1001 Log.w(TAG, "ColorStateList " + getResourceName(id) + " has "
1002 + "unresolved theme attributes! Consider using "
1003 + "Resources.getColorStateList(int, Theme) or "
1004 + "Context.getColorStateList(int).", new RuntimeException());
1005 }
1006 return csl;
1007 }
1008
1009 /**
1010 * Returns a themed color state list associated with a particular resource
1011 * ID. The resource may contain either a single raw color value or a
1012 * complex {@link ColorStateList} holding multiple possible colors.
1013 *
1014 * @param id The desired resource identifier of a {@link ColorStateList},
1015 * as generated by the aapt tool. This integer encodes the
1016 * package, type, and resource entry. The value 0 is an invalid
1017 * identifier.
1018 * @param theme The theme used to style the color attributes, may be
1019 * {@code null}.
1020 *
1021 * @throws NotFoundException Throws NotFoundException if the given ID does
1022 * not exist.
1023 *
1024 * @return A themed ColorStateList object containing either a single solid
1025 * color or multiple colors that can be selected based on a state.
1026 */
1027 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -07001028 public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme)
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001029 throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001030 TypedValue value;
1031 synchronized (mAccessLock) {
1032 value = mTmpValue;
1033 if (value == null) {
1034 value = new TypedValue();
1035 } else {
1036 mTmpValue = null;
1037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 getValue(id, value, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001040
1041 final ColorStateList res = loadColorStateList(value, id, theme);
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001042 synchronized (mAccessLock) {
1043 if (mTmpValue == null) {
1044 mTmpValue = value;
1045 }
1046 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001047
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001048 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
1051 /**
1052 * Return a boolean associated with a particular resource ID. This can be
1053 * used with any integral resource value, and will return true if it is
1054 * non-zero.
1055 *
1056 * @param id The desired resource identifier, as generated by the aapt
1057 * tool. This integer encodes the package, type, and resource
1058 * entry. The value 0 is an invalid identifier.
1059 *
1060 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1061 *
1062 * @return Returns the boolean value contained in the resource.
1063 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001064 public boolean getBoolean(@BoolRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001065 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001067 if (value == null) {
1068 mTmpValue = value = new TypedValue();
1069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 getValue(id, value, true);
1071 if (value.type >= TypedValue.TYPE_FIRST_INT
1072 && value.type <= TypedValue.TYPE_LAST_INT) {
1073 return value.data != 0;
1074 }
1075 throw new NotFoundException(
1076 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
1077 + Integer.toHexString(value.type) + " is not valid");
1078 }
1079 }
1080
1081 /**
1082 * Return an integer associated with a particular resource ID.
1083 *
1084 * @param id The desired resource identifier, as generated by the aapt
1085 * tool. This integer encodes the package, type, and resource
1086 * entry. The value 0 is an invalid identifier.
1087 *
1088 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1089 *
1090 * @return Returns the integer value contained in the resource.
1091 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001092 public int getInteger(@IntegerRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001093 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 TypedValue value = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001095 if (value == null) {
1096 mTmpValue = value = new TypedValue();
1097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 getValue(id, value, true);
1099 if (value.type >= TypedValue.TYPE_FIRST_INT
1100 && value.type <= TypedValue.TYPE_LAST_INT) {
1101 return value.data;
1102 }
1103 throw new NotFoundException(
1104 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
1105 + Integer.toHexString(value.type) + " is not valid");
1106 }
1107 }
1108
1109 /**
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001110 * Retrieve a floating-point value for a particular resource ID.
1111 *
1112 * @param id The desired resource identifier, as generated by the aapt
1113 * tool. This integer encodes the package, type, and resource
1114 * entry. The value 0 is an invalid identifier.
1115 *
1116 * @return Returns the floating-point value contained in the resource.
1117 *
1118 * @throws NotFoundException Throws NotFoundException if the given ID does
1119 * not exist or is not a floating-point value.
1120 * @hide Pending API council approval.
1121 */
1122 public float getFloat(int id) {
1123 synchronized (mAccessLock) {
1124 TypedValue value = mTmpValue;
1125 if (value == null) {
1126 mTmpValue = value = new TypedValue();
1127 }
1128 getValue(id, value, true);
1129 if (value.type == TypedValue.TYPE_FLOAT) {
1130 return value.getFloat();
1131 }
1132 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) + " type #0x"
1133 + Integer.toHexString(value.type) + " is not valid");
1134 }
1135 }
1136
1137 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 * Return an XmlResourceParser through which you can read a view layout
1139 * description for the given resource ID. This parser has limited
1140 * functionality -- in particular, you can't change its input, and only
1141 * the high-level events are available.
1142 *
1143 * <p>This function is really a simple wrapper for calling
1144 * {@link #getXml} with a layout resource.
1145 *
1146 * @param id The desired resource identifier, as generated by the aapt
1147 * tool. This integer encodes the package, type, and resource
1148 * entry. The value 0 is an invalid identifier.
1149 *
1150 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1151 *
1152 * @return A new parser object through which you can read
1153 * the XML data.
1154 *
1155 * @see #getXml
1156 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001157 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 return loadXmlResourceParser(id, "layout");
1159 }
1160
1161 /**
1162 * Return an XmlResourceParser through which you can read an animation
1163 * description for the given resource ID. This parser has limited
1164 * functionality -- in particular, you can't change its input, and only
1165 * the high-level events are available.
1166 *
1167 * <p>This function is really a simple wrapper for calling
1168 * {@link #getXml} with an animation resource.
1169 *
1170 * @param id The desired resource identifier, as generated by the aapt
1171 * tool. This integer encodes the package, type, and resource
1172 * entry. The value 0 is an invalid identifier.
1173 *
1174 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1175 *
1176 * @return A new parser object through which you can read
1177 * the XML data.
1178 *
1179 * @see #getXml
1180 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001181 public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 return loadXmlResourceParser(id, "anim");
1183 }
1184
1185 /**
1186 * Return an XmlResourceParser through which you can read a generic XML
1187 * resource for the given resource ID.
1188 *
1189 * <p>The XmlPullParser implementation returned here has some limited
1190 * functionality. In particular, you can't change its input, and only
1191 * high-level parsing events are available (since the document was
1192 * pre-parsed for you at build time, which involved merging text and
1193 * stripping comments).
1194 *
1195 * @param id The desired resource identifier, as generated by the aapt
1196 * tool. This integer encodes the package, type, and resource
1197 * entry. The value 0 is an invalid identifier.
1198 *
1199 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1200 *
1201 * @return A new parser object through which you can read
1202 * the XML data.
1203 *
1204 * @see android.util.AttributeSet
1205 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001206 public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 return loadXmlResourceParser(id, "xml");
1208 }
1209
1210 /**
1211 * Open a data stream for reading a raw resource. This can only be used
1212 * with resources whose value is the name of an asset files -- that is, it can be
1213 * used to open drawable, sound, and raw resources; it will fail on string
1214 * and color resources.
1215 *
1216 * @param id The resource identifier to open, as generated by the appt
1217 * tool.
1218 *
1219 * @return InputStream Access to the resource data.
1220 *
1221 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1222 *
1223 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001224 public InputStream openRawResource(@RawRes int id) throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001225 TypedValue value;
1226 synchronized (mAccessLock) {
1227 value = mTmpValue;
1228 if (value == null) {
1229 value = new TypedValue();
1230 } else {
1231 mTmpValue = null;
1232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001234 InputStream res = openRawResource(id, value);
1235 synchronized (mAccessLock) {
1236 if (mTmpValue == null) {
1237 mTmpValue = value;
1238 }
1239 }
1240 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
1242
1243 /**
1244 * Open a data stream for reading a raw resource. This can only be used
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001245 * with resources whose value is the name of an asset file -- that is, it can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 * used to open drawable, sound, and raw resources; it will fail on string
1247 * and color resources.
1248 *
1249 * @param id The resource identifier to open, as generated by the appt tool.
1250 * @param value The TypedValue object to hold the resource information.
1251 *
1252 * @return InputStream Access to the resource data.
1253 *
1254 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001256 public InputStream openRawResource(@RawRes int id, TypedValue value)
1257 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 getValue(id, value, true);
1259
1260 try {
1261 return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1262 AssetManager.ACCESS_STREAMING);
1263 } catch (Exception e) {
1264 NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1265 " from drawable resource ID #0x" + Integer.toHexString(id));
1266 rnf.initCause(e);
1267 throw rnf;
1268 }
1269 }
1270
1271 /**
1272 * Open a file descriptor for reading a raw resource. This can only be used
1273 * with resources whose value is the name of an asset files -- that is, it can be
1274 * used to open drawable, sound, and raw resources; it will fail on string
1275 * and color resources.
1276 *
1277 * <p>This function only works for resources that are stored in the package
1278 * as uncompressed data, which typically includes things like mp3 files
1279 * and png images.
1280 *
1281 * @param id The resource identifier to open, as generated by the appt
1282 * tool.
1283 *
1284 * @return AssetFileDescriptor A new file descriptor you can use to read
1285 * the resource. This includes the file descriptor itself, as well as the
1286 * offset and length of data where the resource appears in the file. A
1287 * null is returned if the file exists but is compressed.
1288 *
1289 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1290 *
1291 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001292 public AssetFileDescriptor openRawResourceFd(@RawRes int id)
1293 throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001294 TypedValue value;
1295 synchronized (mAccessLock) {
1296 value = mTmpValue;
1297 if (value == null) {
1298 value = new TypedValue();
1299 } else {
1300 mTmpValue = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001302 getValue(id, value, true);
1303 }
1304 try {
1305 return mAssets.openNonAssetFd(
1306 value.assetCookie, value.string.toString());
1307 } catch (Exception e) {
1308 NotFoundException rnf = new NotFoundException(
1309 "File " + value.string.toString()
1310 + " from drawable resource ID #0x"
1311 + Integer.toHexString(id));
1312 rnf.initCause(e);
1313 throw rnf;
1314 } finally {
1315 synchronized (mAccessLock) {
1316 if (mTmpValue == null) {
1317 mTmpValue = value;
1318 }
1319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321 }
1322
1323 /**
1324 * Return the raw data associated with a particular resource ID.
1325 *
1326 * @param id The desired resource identifier, as generated by the aapt
1327 * tool. This integer encodes the package, type, and resource
1328 * entry. The value 0 is an invalid identifier.
1329 * @param outValue Object in which to place the resource data.
1330 * @param resolveRefs If true, a resource that is a reference to another
1331 * resource will be followed so that you receive the
1332 * actual final resource data. If false, the TypedValue
1333 * will be filled in with the reference itself.
1334 *
1335 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1336 *
1337 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001338 public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001340 boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 if (found) {
1342 return;
1343 }
1344 throw new NotFoundException("Resource ID #0x"
1345 + Integer.toHexString(id));
1346 }
1347
1348 /**
Kenny Root55fc8502010-10-28 14:47:01 -07001349 * Get the raw value associated with a resource with associated density.
1350 *
1351 * @param id resource identifier
1352 * @param density density in DPI
1353 * @param resolveRefs If true, a resource that is a reference to another
1354 * resource will be followed so that you receive the actual final
1355 * resource data. If false, the TypedValue will be filled in with
1356 * the reference itself.
1357 * @throws NotFoundException Throws NotFoundException if the given ID does
1358 * not exist.
1359 * @see #getValue(String, TypedValue, boolean)
Kenny Root55fc8502010-10-28 14:47:01 -07001360 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001361 public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
1362 boolean resolveRefs) throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001363 boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1364 if (found) {
1365 return;
1366 }
1367 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1368 }
1369
1370 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 * Return the raw data associated with a particular resource ID.
1372 * See getIdentifier() for information on how names are mapped to resource
1373 * IDs, and getString(int) for information on how string resources are
1374 * retrieved.
1375 *
1376 * <p>Note: use of this function is discouraged. It is much more
1377 * efficient to retrieve resources by identifier than by name.
1378 *
1379 * @param name The name of the desired resource. This is passed to
1380 * getIdentifier() with a default type of "string".
1381 * @param outValue Object in which to place the resource data.
1382 * @param resolveRefs If true, a resource that is a reference to another
1383 * resource will be followed so that you receive the
1384 * actual final resource data. If false, the TypedValue
1385 * will be filled in with the reference itself.
1386 *
1387 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1388 *
1389 */
1390 public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1391 throws NotFoundException {
1392 int id = getIdentifier(name, "string", null);
1393 if (id != 0) {
1394 getValue(id, outValue, resolveRefs);
1395 return;
1396 }
1397 throw new NotFoundException("String resource name " + name);
1398 }
1399
1400 /**
1401 * This class holds the current attribute values for a particular theme.
1402 * In other words, a Theme is a set of values for resource attributes;
1403 * these are used in conjunction with {@link TypedArray}
1404 * to resolve the final value for an attribute.
1405 *
1406 * <p>The Theme's attributes come into play in two ways: (1) a styled
1407 * attribute can explicit reference a value in the theme through the
1408 * "?themeAttribute" syntax; (2) if no value has been defined for a
1409 * particular styled attribute, as a last resort we will try to find that
1410 * attribute's value in the Theme.
1411 *
1412 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1413 * retrieve XML attributes with style and theme information applied.
1414 */
1415 public final class Theme {
1416 /**
1417 * Place new attribute values into the theme. The style resource
1418 * specified by <var>resid</var> will be retrieved from this Theme's
1419 * resources, its values placed into the Theme object.
1420 *
1421 * <p>The semantics of this function depends on the <var>force</var>
1422 * argument: If false, only values that are not already defined in
1423 * the theme will be copied from the system resource; otherwise, if
1424 * any of the style's attributes are already defined in the theme, the
1425 * current values in the theme will be overwritten.
1426 *
Alan Viverette75257ce2014-05-22 19:31:38 -07001427 * @param resId The resource ID of a style resource from which to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 * obtain attribute values.
1429 * @param force If true, values in the style resource will always be
1430 * used in the theme; otherwise, they will only be used
1431 * if not already defined in the theme.
1432 */
Alan Viverette75257ce2014-05-22 19:31:38 -07001433 public void applyStyle(int resId, boolean force) {
1434 AssetManager.applyThemeStyle(mTheme, resId, force);
Alan Viverette52b999f2014-03-24 18:00:26 -07001435
Alan Viverette75257ce2014-05-22 19:31:38 -07001436 mThemeResId = resId;
1437 mKey += Integer.toHexString(resId) + (force ? "! " : " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439
1440 /**
1441 * Set this theme to hold the same contents as the theme
1442 * <var>other</var>. If both of these themes are from the same
1443 * Resources object, they will be identical after this function
1444 * returns. If they are from different Resources, only the resources
1445 * they have in common will be set in this theme.
1446 *
1447 * @param other The existing Theme to copy from.
1448 */
1449 public void setTo(Theme other) {
1450 AssetManager.copyTheme(mTheme, other.mTheme);
Alan Viverette52b999f2014-03-24 18:00:26 -07001451
Alan Viverette52b999f2014-03-24 18:00:26 -07001452 mThemeResId = other.mThemeResId;
Alan Viverette75257ce2014-05-22 19:31:38 -07001453 mKey = other.mKey;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 }
1455
1456 /**
John Spurlock330dd532012-12-18 12:03:11 -05001457 * Return a TypedArray holding the values defined by
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 * <var>Theme</var> which are listed in <var>attrs</var>.
1459 *
Scott Main183bf112012-08-13 19:12:13 -07001460 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1461 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 *
1463 * @param attrs The desired attributes.
1464 *
1465 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1466 *
1467 * @return Returns a TypedArray holding an array of the attribute values.
1468 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1469 * when done with it.
1470 *
1471 * @see Resources#obtainAttributes
1472 * @see #obtainStyledAttributes(int, int[])
1473 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1474 */
1475 public TypedArray obtainStyledAttributes(int[] attrs) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001476 final int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001477 final TypedArray array = TypedArray.obtain(Resources.this, len);
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001478 array.mTheme = this;
Alan Viverette52b999f2014-03-24 18:00:26 -07001479 AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 return array;
1481 }
1482
1483 /**
John Spurlock330dd532012-12-18 12:03:11 -05001484 * Return a TypedArray holding the values defined by the style
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 * resource <var>resid</var> which are listed in <var>attrs</var>.
1486 *
Scott Main183bf112012-08-13 19:12:13 -07001487 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1488 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 *
1490 * @param resid The desired style resource.
1491 * @param attrs The desired attributes in the style.
1492 *
1493 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1494 *
1495 * @return Returns a TypedArray holding an array of the attribute values.
1496 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1497 * when done with it.
1498 *
1499 * @see Resources#obtainAttributes
1500 * @see #obtainStyledAttributes(int[])
1501 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1502 */
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001503 public TypedArray obtainStyledAttributes(int resid, int[] attrs) throws NotFoundException {
1504 final int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001505 final TypedArray array = TypedArray.obtain(Resources.this, len);
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001506 array.mTheme = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 if (false) {
1508 int[] data = array.mData;
1509
1510 System.out.println("**********************************************************");
1511 System.out.println("**********************************************************");
1512 System.out.println("**********************************************************");
1513 System.out.println("Attributes:");
1514 String s = " Attrs:";
1515 int i;
1516 for (i=0; i<attrs.length; i++) {
1517 s = s + " 0x" + Integer.toHexString(attrs[i]);
1518 }
1519 System.out.println(s);
1520 s = " Found:";
1521 TypedValue value = new TypedValue();
1522 for (i=0; i<attrs.length; i++) {
1523 int d = i*AssetManager.STYLE_NUM_ENTRIES;
1524 value.type = data[d+AssetManager.STYLE_TYPE];
1525 value.data = data[d+AssetManager.STYLE_DATA];
1526 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1527 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1528 s = s + " 0x" + Integer.toHexString(attrs[i])
1529 + "=" + value;
1530 }
1531 System.out.println(s);
1532 }
Alan Viverette52b999f2014-03-24 18:00:26 -07001533 AssetManager.applyStyle(mTheme, 0, resid, 0, attrs, array.mData, array.mIndices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 return array;
1535 }
1536
1537 /**
John Spurlock330dd532012-12-18 12:03:11 -05001538 * Return a TypedArray holding the attribute values in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * <var>set</var>
1540 * that are listed in <var>attrs</var>. In addition, if the given
1541 * AttributeSet specifies a style class (through the "style" attribute),
1542 * that style will be applied on top of the base attributes it defines.
1543 *
Scott Main183bf112012-08-13 19:12:13 -07001544 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1545 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 *
1547 * <p>When determining the final value of a particular attribute, there
1548 * are four inputs that come into play:</p>
1549 *
1550 * <ol>
1551 * <li> Any attribute values in the given AttributeSet.
1552 * <li> The style resource specified in the AttributeSet (named
1553 * "style").
1554 * <li> The default style specified by <var>defStyleAttr</var> and
1555 * <var>defStyleRes</var>
1556 * <li> The base values in this theme.
1557 * </ol>
1558 *
1559 * <p>Each of these inputs is considered in-order, with the first listed
1560 * taking precedence over the following ones. In other words, if in the
1561 * AttributeSet you have supplied <code>&lt;Button
1562 * textColor="#ff000000"&gt;</code>, then the button's text will
1563 * <em>always</em> be black, regardless of what is specified in any of
1564 * the styles.
1565 *
1566 * @param set The base set of attribute values. May be null.
1567 * @param attrs The desired attributes to be retrieved.
1568 * @param defStyleAttr An attribute in the current theme that contains a
1569 * reference to a style resource that supplies
John Spurlock330dd532012-12-18 12:03:11 -05001570 * defaults values for the TypedArray. Can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 * 0 to not look for defaults.
1572 * @param defStyleRes A resource identifier of a style resource that
John Spurlock330dd532012-12-18 12:03:11 -05001573 * supplies default values for the TypedArray,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 * used only if defStyleAttr is 0 or can not be found
1575 * in the theme. Can be 0 to not look for defaults.
1576 *
1577 * @return Returns a TypedArray holding an array of the attribute values.
1578 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1579 * when done with it.
1580 *
1581 * @see Resources#obtainAttributes
1582 * @see #obtainStyledAttributes(int[])
1583 * @see #obtainStyledAttributes(int, int[])
1584 */
1585 public TypedArray obtainStyledAttributes(AttributeSet set,
1586 int[] attrs, int defStyleAttr, int defStyleRes) {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001587 final int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001588 final TypedArray array = TypedArray.obtain(Resources.this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589
1590 // XXX note that for now we only work with compiled XML files.
1591 // To support generic XML files we will need to manually parse
1592 // out the attributes from the XML file (applying type information
1593 // contained in the resources and such).
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001594 final XmlBlock.Parser parser = (XmlBlock.Parser)set;
1595 AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1596 parser != null ? parser.mParseState : 0, attrs, array.mData, array.mIndices);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001598 array.mTheme = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 array.mXml = parser;
1600
1601 if (false) {
1602 int[] data = array.mData;
1603
1604 System.out.println("Attributes:");
1605 String s = " Attrs:";
1606 int i;
1607 for (i=0; i<set.getAttributeCount(); i++) {
1608 s = s + " " + set.getAttributeName(i);
1609 int id = set.getAttributeNameResource(i);
1610 if (id != 0) {
1611 s = s + "(0x" + Integer.toHexString(id) + ")";
1612 }
1613 s = s + "=" + set.getAttributeValue(i);
1614 }
1615 System.out.println(s);
1616 s = " Found:";
1617 TypedValue value = new TypedValue();
1618 for (i=0; i<attrs.length; i++) {
1619 int d = i*AssetManager.STYLE_NUM_ENTRIES;
1620 value.type = data[d+AssetManager.STYLE_TYPE];
1621 value.data = data[d+AssetManager.STYLE_DATA];
1622 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];
1623 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];
1624 s = s + " 0x" + Integer.toHexString(attrs[i])
1625 + "=" + value;
1626 }
1627 System.out.println(s);
1628 }
1629
1630 return array;
1631 }
1632
1633 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001634 * Retrieve the values for a set of attributes in the Theme. The
1635 * contents of the typed array are ultimately filled in by
1636 * {@link Resources#getValue}.
1637 *
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001638 * @param values The base set of attribute values, must be equal in
1639 * length to {@code attrs}. All values must be of type
1640 * {@link TypedValue#TYPE_ATTRIBUTE}.
Alan Viverette52b999f2014-03-24 18:00:26 -07001641 * @param attrs The desired attributes to be retrieved.
Alan Viverette52b999f2014-03-24 18:00:26 -07001642 * @return Returns a TypedArray holding an array of the attribute
1643 * values. Be sure to call {@link TypedArray#recycle()}
1644 * when done with it.
1645 * @hide
1646 */
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001647 @NonNull
1648 public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
Alan Viverette52b999f2014-03-24 18:00:26 -07001649 final int len = attrs.length;
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001650 if (values == null || len != values.length) {
Alan Viverette52b999f2014-03-24 18:00:26 -07001651 throw new IllegalArgumentException(
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001652 "Base attribute values must the same length as attrs");
Alan Viverette52b999f2014-03-24 18:00:26 -07001653 }
1654
1655 final TypedArray array = TypedArray.obtain(Resources.this, len);
Alan Viverette0cfb8772014-05-14 17:40:53 -07001656 AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
Alan Viverette52b999f2014-03-24 18:00:26 -07001657 array.mTheme = this;
1658 array.mXml = null;
1659
1660 return array;
1661 }
1662
1663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * Retrieve the value of an attribute in the Theme. The contents of
1665 * <var>outValue</var> are ultimately filled in by
1666 * {@link Resources#getValue}.
1667 *
1668 * @param resid The resource identifier of the desired theme
1669 * attribute.
1670 * @param outValue Filled in with the ultimate resource value supplied
1671 * by the attribute.
1672 * @param resolveRefs If true, resource references will be walked; if
1673 * false, <var>outValue</var> may be a
1674 * TYPE_REFERENCE. In either case, it will never
1675 * be a TYPE_ATTRIBUTE.
1676 *
1677 * @return boolean Returns true if the attribute was found and
1678 * <var>outValue</var> is valid, else false.
1679 */
Alan Viverette52b999f2014-03-24 18:00:26 -07001680 public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1682 if (false) {
1683 System.out.println(
1684 "resolveAttribute #" + Integer.toHexString(resid)
1685 + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type)
1686 + ", data=0x" + Integer.toHexString(outValue.data));
1687 }
1688 return got;
1689 }
1690
1691 /**
Jon Miranda042ad632014-09-03 17:57:35 -07001692 * Gets all of the attribute ids associated with this {@link Theme}. For debugging only.
1693 *
1694 * @return The int array containing attribute ids associated with this {@link Theme}.
1695 * @hide
1696 */
1697 public int[] getAllAttributes() {
1698 return mAssets.getStyleAttributes(getAppliedStyleResId());
1699 }
1700
1701 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001702 * Returns the resources to which this theme belongs.
1703 *
1704 * @return Resources to which this theme belongs.
1705 */
1706 public Resources getResources() {
1707 return Resources.this;
1708 }
1709
1710 /**
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001711 * Return a drawable object associated with a particular resource ID
1712 * and styled for the Theme.
1713 *
1714 * @param id The desired resource identifier, as generated by the aapt
1715 * tool. This integer encodes the package, type, and resource
1716 * entry. The value 0 is an invalid identifier.
1717 * @return Drawable An object that can be used to draw this resource.
1718 * @throws NotFoundException Throws NotFoundException if the given ID
1719 * does not exist.
1720 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001721 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001722 return Resources.this.getDrawable(id, this);
1723 }
1724
1725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 * Print contents of this theme out to the log. For debugging only.
1727 *
1728 * @param priority The log priority to use.
1729 * @param tag The log tag to use.
1730 * @param prefix Text to prefix each line printed.
1731 */
1732 public void dump(int priority, String tag, String prefix) {
1733 AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1734 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001735
1736 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 protected void finalize() throws Throwable {
1738 super.finalize();
1739 mAssets.releaseTheme(mTheme);
1740 }
1741
1742 /*package*/ Theme() {
1743 mAssets = Resources.this.mAssets;
1744 mTheme = mAssets.createTheme();
1745 }
1746
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001747 @SuppressWarnings("hiding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 private final AssetManager mAssets;
Ashok Bhat896043d2014-01-17 16:02:38 +00001749 private final long mTheme;
Alan Viverette52b999f2014-03-24 18:00:26 -07001750
Alan Viverette351f0c12014-03-28 15:25:27 -07001751 /** Resource identifier for the theme. */
Alan Viverette52b999f2014-03-24 18:00:26 -07001752 private int mThemeResId = 0;
Deepanshu Guptabfec73c2014-03-11 18:02:44 -07001753
Alan Viverette75257ce2014-05-22 19:31:38 -07001754 /** Unique key for the series of styles applied to this theme. */
1755 private String mKey = "";
1756
Deepanshu Guptabfec73c2014-03-11 18:02:44 -07001757 // Needed by layoutlib.
1758 /*package*/ long getNativeTheme() {
1759 return mTheme;
1760 }
1761
1762 /*package*/ int getAppliedStyleResId() {
1763 return mThemeResId;
1764 }
Alan Viverette75257ce2014-05-22 19:31:38 -07001765
1766 /*package*/ String getKey() {
1767 return mKey;
1768 }
Jon Miranda836c0a82014-08-11 12:32:26 -07001769
1770 private String getResourceNameFromHexString(String hexString) {
1771 return getResourceName(Integer.parseInt(hexString, 16));
1772 }
1773
1774 /**
1775 * Parses {@link #mKey} and returns a String array that holds pairs of adjacent Theme data:
1776 * resource name followed by whether or not it was forced, as specified by
1777 * {@link #applyStyle(int, boolean)}.
1778 *
1779 * @hide
1780 */
1781 @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
1782 public String[] getTheme() {
1783 String[] themeData = mKey.split(" ");
1784 String[] themes = new String[themeData.length * 2];
1785 String theme;
1786 boolean forced;
1787
1788 for (int i = 0, j = themeData.length - 1; i < themes.length; i += 2, --j) {
1789 theme = themeData[j];
1790 forced = theme.endsWith("!");
1791 themes[i] = forced ?
1792 getResourceNameFromHexString(theme.substring(0, theme.length() - 1)) :
1793 getResourceNameFromHexString(theme);
1794 themes[i + 1] = forced ? "forced" : "not forced";
1795 }
1796 return themes;
1797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 }
1799
1800 /**
1801 * Generate a new Theme object for this set of Resources. It initially
1802 * starts out empty.
Jon Miranda836c0a82014-08-11 12:32:26 -07001803 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 * @return Theme The newly created Theme container.
1805 */
1806 public final Theme newTheme() {
1807 return new Theme();
1808 }
1809
1810 /**
1811 * Retrieve a set of basic attribute values from an AttributeSet, not
1812 * performing styling of them using a theme and/or style resources.
Jon Miranda836c0a82014-08-11 12:32:26 -07001813 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 * @param set The current attribute values to retrieve.
1815 * @param attrs The specific attributes to be retrieved.
1816 * @return Returns a TypedArray holding an array of the attribute values.
1817 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1818 * when done with it.
1819 *
1820 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1821 */
1822 public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1823 int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001824 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825
1826 // XXX note that for now we only work with compiled XML files.
1827 // To support generic XML files we will need to manually parse
1828 // out the attributes from the XML file (applying type information
1829 // contained in the resources and such).
1830 XmlBlock.Parser parser = (XmlBlock.Parser)set;
1831 mAssets.retrieveAttributes(parser.mParseState, attrs,
1832 array.mData, array.mIndices);
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 array.mXml = parser;
1835
1836 return array;
1837 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 /**
1840 * Store the newly updated configuration.
1841 */
1842 public void updateConfiguration(Configuration config,
1843 DisplayMetrics metrics) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001844 updateConfiguration(config, metrics, null);
1845 }
1846
1847 /**
1848 * @hide
1849 */
1850 public void updateConfiguration(Configuration config,
1851 DisplayMetrics metrics, CompatibilityInfo compat) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001852 synchronized (mAccessLock) {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001853 if (false) {
1854 Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1855 + mConfiguration + " old compat is " + mCompatibilityInfo);
1856 Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1857 + config + " new compat is " + compat);
1858 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001859 if (compat != null) {
1860 mCompatibilityInfo = compat;
1861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 if (metrics != null) {
1863 mMetrics.setTo(metrics);
1864 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001865 // NOTE: We should re-arrange this code to create a Display
1866 // with the CompatibilityInfo that is used everywhere we deal
1867 // with the display in relation to this app, rather than
1868 // doing the conversion here. This impl should be okay because
1869 // we make sure to return a compatible display in the places
1870 // where there are public APIs to retrieve the display... but
1871 // it would be cleaner and more maintainble to just be
1872 // consistently dealing with a compatible display everywhere in
1873 // the framework.
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07001874 mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1875
Alan Viverettea8636c92015-03-27 10:44:39 -07001876 final int configChanges = calcConfigChanges(config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001877 if (mConfiguration.locale == null) {
1878 mConfiguration.locale = Locale.getDefault();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001879 mConfiguration.setLayoutDirection(mConfiguration.locale);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001880 }
Dianne Hackborn756220b2012-08-14 16:45:30 -07001881 if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1882 mMetrics.densityDpi = mConfiguration.densityDpi;
1883 mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1884 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001885 mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 String locale = null;
1888 if (mConfiguration.locale != null) {
Deepanshu Gupta5cd9dde2014-07-14 15:50:49 -07001889 locale = adjustLanguageTag(mConfiguration.locale.toLanguageTag());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001891
1892 final int width, height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1894 width = mMetrics.widthPixels;
1895 height = mMetrics.heightPixels;
1896 } else {
1897 //noinspection SuspiciousNameCombination
1898 width = mMetrics.heightPixels;
1899 //noinspection SuspiciousNameCombination
1900 height = mMetrics.widthPixels;
1901 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001902
1903 final int keyboardHidden;
1904 if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1905 && mConfiguration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
Alan Viverettea8636c92015-03-27 10:44:39 -07001907 } else {
1908 keyboardHidden = mConfiguration.keyboardHidden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
1912 locale, mConfiguration.orientation,
1913 mConfiguration.touchscreen,
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001914 mConfiguration.densityDpi, mConfiguration.keyboard,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 keyboardHidden, mConfiguration.navigation, width, height,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07001916 mConfiguration.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07001917 mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08001918 mConfiguration.screenLayout, mConfiguration.uiMode,
1919 Build.VERSION.RESOURCES_SDK_INT);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001920
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001921 if (DEBUG_CONFIG) {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001922 Slog.i(TAG, "**** Updating config of " + this + ": final config is " + mConfiguration
1923 + " final compat is " + mCompatibilityInfo);
1924 }
1925
Alan Viverette52b999f2014-03-24 18:00:26 -07001926 clearDrawableCachesLocked(mDrawableCache, configChanges);
1927 clearDrawableCachesLocked(mColorDrawableCache, configChanges);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001928 mColorStateListCache.onConfigurationChange(configChanges);
Yigit Boyard422dc32014-09-25 12:23:35 -07001929 mAnimatorCache.onConfigurationChange(configChanges);
1930 mStateListAnimatorCache.onConfigurationChange(configChanges);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 flushLayoutCache();
1933 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001934 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 if (mPluralRule != null) {
Elliott Hughes1ad636c2010-07-01 16:51:48 -07001936 mPluralRule = NativePluralRules.forLocale(config.locale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938 }
1939 }
1940
Yigit Boyard422dc32014-09-25 12:23:35 -07001941 /**
1942 * Called by ConfigurationBoundResourceCacheTest via reflection.
1943 */
1944 private int calcConfigChanges(Configuration config) {
1945 int configChanges = 0xfffffff;
1946 if (config != null) {
1947 mTmpConfig.setTo(config);
1948 int density = config.densityDpi;
1949 if (density == Configuration.DENSITY_DPI_UNDEFINED) {
1950 density = mMetrics.noncompatDensityDpi;
1951 }
1952
1953 mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
1954
1955 if (mTmpConfig.locale == null) {
1956 mTmpConfig.locale = Locale.getDefault();
1957 mTmpConfig.setLayoutDirection(mTmpConfig.locale);
1958 }
1959 configChanges = mConfiguration.updateFrom(mTmpConfig);
1960 configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
1961 }
1962 return configChanges;
1963 }
1964
Alan Viverette52b999f2014-03-24 18:00:26 -07001965 private void clearDrawableCachesLocked(
Alan Viverette75257ce2014-05-22 19:31:38 -07001966 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches,
1967 int configChanges) {
Alan Viverette52b999f2014-03-24 18:00:26 -07001968 final int N = caches.size();
1969 for (int i = 0; i < N; i++) {
1970 clearDrawableCacheLocked(caches.valueAt(i), configChanges);
1971 }
1972 }
1973
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001974 private void clearDrawableCacheLocked(
Alan Viverette52b999f2014-03-24 18:00:26 -07001975 LongSparseArray<WeakReference<ConstantState>> cache, int configChanges) {
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001976 if (DEBUG_CONFIG) {
1977 Log.d(TAG, "Cleaning up drawables config changes: 0x"
1978 + Integer.toHexString(configChanges));
1979 }
Alan Viverette52b999f2014-03-24 18:00:26 -07001980 final int N = cache.size();
1981 for (int i = 0; i < N; i++) {
1982 final WeakReference<ConstantState> ref = cache.valueAt(i);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001983 if (ref != null) {
Alan Viverette52b999f2014-03-24 18:00:26 -07001984 final ConstantState cs = ref.get();
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001985 if (cs != null) {
1986 if (Configuration.needNewResources(
1987 configChanges, cs.getChangingConfigurations())) {
1988 if (DEBUG_CONFIG) {
1989 Log.d(TAG, "FLUSHING #0x"
Alan Viverette75257ce2014-05-22 19:31:38 -07001990 + Long.toHexString(cache.keyAt(i))
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001991 + " / " + cs + " with changes: 0x"
1992 + Integer.toHexString(cs.getChangingConfigurations()));
1993 }
1994 cache.setValueAt(i, null);
1995 } else if (DEBUG_CONFIG) {
1996 Log.d(TAG, "(Keeping #0x"
1997 + Long.toHexString(cache.keyAt(i))
1998 + " / " + cs + " with changes: 0x"
1999 + Integer.toHexString(cs.getChangingConfigurations())
2000 + ")");
2001 }
2002 }
2003 }
2004 }
Masanori Oginoc7d9d272010-07-10 12:10:41 +09002005 }
2006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 /**
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002008 * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
2009 * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
2010 *
2011 * All released versions of android prior to "L" used the deprecated language
2012 * tags, so we will need to support them for backwards compatibility.
2013 *
2014 * Note that this conversion needs to take place *after* the call to
2015 * {@code toLanguageTag} because that will convert all the deprecated codes to
2016 * the new ones, even if they're set manually.
2017 */
2018 private static String adjustLanguageTag(String languageTag) {
2019 final int separator = languageTag.indexOf('-');
2020 final String language;
2021 final String remainder;
2022
2023 if (separator == -1) {
2024 language = languageTag;
2025 remainder = "";
2026 } else {
2027 language = languageTag.substring(0, separator);
2028 remainder = languageTag.substring(separator);
2029 }
2030
Narayan Kamath4c6ce232014-07-18 16:09:36 +01002031 return Locale.adjustLanguageCode(language) + remainder;
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002032 }
2033
2034 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 * Update the system resources configuration if they have previously
2036 * been initialized.
2037 *
2038 * @hide
2039 */
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002040 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
2041 CompatibilityInfo compat) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if (mSystem != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002043 mSystem.updateConfiguration(config, metrics, compat);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 //Log.i(TAG, "Updated system resources " + mSystem
2045 // + ": " + mSystem.getConfiguration());
2046 }
2047 }
2048
2049 /**
2050 * Return the current display metrics that are in effect for this resource
2051 * object. The returned object should be treated as read-only.
2052 *
2053 * @return The resource's current display metrics.
2054 */
2055 public DisplayMetrics getDisplayMetrics() {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002056 if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
2057 + "x" + mMetrics.heightPixels + " " + mMetrics.density);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 return mMetrics;
2059 }
2060
2061 /**
2062 * Return the current configuration that is in effect for this resource
2063 * object. The returned object should be treated as read-only.
2064 *
2065 * @return The resource's current configuration.
2066 */
2067 public Configuration getConfiguration() {
2068 return mConfiguration;
2069 }
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002070
2071 /**
2072 * Return the compatibility mode information for the application.
2073 * The returned object should be treated as read-only.
2074 *
Dianne Hackborn3904d032011-05-27 12:09:11 -07002075 * @return compatibility info.
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002076 * @hide
2077 */
2078 public CompatibilityInfo getCompatibilityInfo() {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002079 return mCompatibilityInfo;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081
2082 /**
Dianne Hackborna53b8282009-07-17 11:13:48 -07002083 * This is just for testing.
2084 * @hide
2085 */
2086 public void setCompatibilityInfo(CompatibilityInfo ci) {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002087 if (ci != null) {
2088 mCompatibilityInfo = ci;
2089 updateConfiguration(mConfiguration, mMetrics);
2090 }
Dianne Hackborna53b8282009-07-17 11:13:48 -07002091 }
2092
2093 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 * Return a resource identifier for the given resource name. A fully
2095 * qualified resource name is of the form "package:type/entry". The first
2096 * two components (package and type) are optional if defType and
2097 * defPackage, respectively, are specified here.
2098 *
2099 * <p>Note: use of this function is discouraged. It is much more
2100 * efficient to retrieve resources by identifier than by name.
2101 *
2102 * @param name The name of the desired resource.
2103 * @param defType Optional default resource type to find, if "type/" is
2104 * not included in the name. Can be null to require an
2105 * explicit type.
2106 * @param defPackage Optional default package to find, if "package:" is
2107 * not included in the name. Can be null to require an
2108 * explicit package.
2109 *
2110 * @return int The associated resource identifier. Returns 0 if no such
2111 * resource was found. (0 is not a valid resource ID.)
2112 */
2113 public int getIdentifier(String name, String defType, String defPackage) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002114 if (name == null) {
2115 throw new NullPointerException("name is null");
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 try {
2118 return Integer.parseInt(name);
2119 } catch (Exception e) {
2120 // Ignore
2121 }
2122 return mAssets.getResourceIdentifier(name, defType, defPackage);
2123 }
2124
2125 /**
Jeff Sharkey47b50332013-03-15 14:46:46 -07002126 * Return true if given resource identifier includes a package.
2127 *
2128 * @hide
2129 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002130 public static boolean resourceHasPackage(@AnyRes int resid) {
Jeff Sharkey47b50332013-03-15 14:46:46 -07002131 return (resid >>> 24) != 0;
2132 }
2133
2134 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 * Return the full name for a given resource identifier. This name is
2136 * a single string of the form "package:type/entry".
2137 *
2138 * @param resid The resource identifier whose name is to be retrieved.
2139 *
2140 * @return A string holding the name of the resource.
2141 *
2142 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2143 *
2144 * @see #getResourcePackageName
2145 * @see #getResourceTypeName
2146 * @see #getResourceEntryName
2147 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002148 public String getResourceName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 String str = mAssets.getResourceName(resid);
2150 if (str != null) return str;
2151 throw new NotFoundException("Unable to find resource ID #0x"
2152 + Integer.toHexString(resid));
2153 }
2154
2155 /**
2156 * Return the package name for a given resource identifier.
2157 *
2158 * @param resid The resource identifier whose package name is to be
2159 * retrieved.
2160 *
2161 * @return A string holding the package name of the resource.
2162 *
2163 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2164 *
2165 * @see #getResourceName
2166 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002167 public String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 String str = mAssets.getResourcePackageName(resid);
2169 if (str != null) return str;
2170 throw new NotFoundException("Unable to find resource ID #0x"
2171 + Integer.toHexString(resid));
2172 }
2173
2174 /**
2175 * Return the type name for a given resource identifier.
2176 *
2177 * @param resid The resource identifier whose type name is to be
2178 * retrieved.
2179 *
2180 * @return A string holding the type name of the resource.
2181 *
2182 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2183 *
2184 * @see #getResourceName
2185 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002186 public String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 String str = mAssets.getResourceTypeName(resid);
2188 if (str != null) return str;
2189 throw new NotFoundException("Unable to find resource ID #0x"
2190 + Integer.toHexString(resid));
2191 }
2192
2193 /**
2194 * Return the entry name for a given resource identifier.
2195 *
2196 * @param resid The resource identifier whose entry name is to be
2197 * retrieved.
2198 *
2199 * @return A string holding the entry name of the resource.
2200 *
2201 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2202 *
2203 * @see #getResourceName
2204 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002205 public String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 String str = mAssets.getResourceEntryName(resid);
2207 if (str != null) return str;
2208 throw new NotFoundException("Unable to find resource ID #0x"
2209 + Integer.toHexString(resid));
2210 }
2211
2212 /**
2213 * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2214 * an XML file. You call this when you are at the parent tag of the
Dianne Hackborndef15372010-08-15 12:43:52 -07002215 * extra tags, and it will return once all of the child tags have been parsed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 * This will call {@link #parseBundleExtra} for each extra tag encountered.
2217 *
2218 * @param parser The parser from which to retrieve the extras.
2219 * @param outBundle A Bundle in which to place all parsed extras.
2220 * @throws XmlPullParserException
2221 * @throws IOException
2222 */
2223 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2224 throws XmlPullParserException, IOException {
2225 int outerDepth = parser.getDepth();
2226 int type;
2227 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2228 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2229 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2230 continue;
2231 }
2232
2233 String nodeName = parser.getName();
2234 if (nodeName.equals("extra")) {
2235 parseBundleExtra("extra", parser, outBundle);
2236 XmlUtils.skipCurrentTag(parser);
2237
2238 } else {
2239 XmlUtils.skipCurrentTag(parser);
2240 }
2241 }
2242 }
2243
2244 /**
2245 * Parse a name/value pair out of an XML tag holding that data. The
2246 * AttributeSet must be holding the data defined by
2247 * {@link android.R.styleable#Extra}. The following value types are supported:
2248 * <ul>
2249 * <li> {@link TypedValue#TYPE_STRING}:
2250 * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2251 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2252 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2253 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2254 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2255 * <li> {@link TypedValue#TYPE_FLOAT}:
2256 * {@link Bundle#putCharSequence Bundle.putFloat()}
2257 * </ul>
2258 *
2259 * @param tagName The name of the tag these attributes come from; this is
2260 * only used for reporting error messages.
2261 * @param attrs The attributes from which to retrieve the name/value pair.
2262 * @param outBundle The Bundle in which to place the parsed value.
2263 * @throws XmlPullParserException If the attributes are not valid.
2264 */
2265 public void parseBundleExtra(String tagName, AttributeSet attrs,
2266 Bundle outBundle) throws XmlPullParserException {
2267 TypedArray sa = obtainAttributes(attrs,
2268 com.android.internal.R.styleable.Extra);
2269
2270 String name = sa.getString(
2271 com.android.internal.R.styleable.Extra_name);
2272 if (name == null) {
2273 sa.recycle();
2274 throw new XmlPullParserException("<" + tagName
2275 + "> requires an android:name attribute at "
2276 + attrs.getPositionDescription());
2277 }
2278
2279 TypedValue v = sa.peekValue(
2280 com.android.internal.R.styleable.Extra_value);
2281 if (v != null) {
2282 if (v.type == TypedValue.TYPE_STRING) {
2283 CharSequence cs = v.coerceToString();
2284 outBundle.putCharSequence(name, cs);
2285 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2286 outBundle.putBoolean(name, v.data != 0);
2287 } else if (v.type >= TypedValue.TYPE_FIRST_INT
2288 && v.type <= TypedValue.TYPE_LAST_INT) {
2289 outBundle.putInt(name, v.data);
2290 } else if (v.type == TypedValue.TYPE_FLOAT) {
2291 outBundle.putFloat(name, v.getFloat());
2292 } else {
2293 sa.recycle();
2294 throw new XmlPullParserException("<" + tagName
2295 + "> only supports string, integer, float, color, and boolean at "
2296 + attrs.getPositionDescription());
2297 }
2298 } else {
2299 sa.recycle();
2300 throw new XmlPullParserException("<" + tagName
2301 + "> requires an android:value or android:resource attribute at "
2302 + attrs.getPositionDescription());
2303 }
2304
2305 sa.recycle();
2306 }
2307
2308 /**
2309 * Retrieve underlying AssetManager storage for these resources.
2310 */
2311 public final AssetManager getAssets() {
2312 return mAssets;
2313 }
2314
2315 /**
2316 * Call this to remove all cached loaded layout resources from the
2317 * Resources object. Only intended for use with performance testing
2318 * tools.
2319 */
2320 public final void flushLayoutCache() {
2321 synchronized (mCachedXmlBlockIds) {
2322 // First see if this block is in our cache.
2323 final int num = mCachedXmlBlockIds.length;
2324 for (int i=0; i<num; i++) {
2325 mCachedXmlBlockIds[i] = -0;
2326 XmlBlock oldBlock = mCachedXmlBlocks[i];
2327 if (oldBlock != null) {
2328 oldBlock.close();
2329 }
2330 mCachedXmlBlocks[i] = null;
2331 }
2332 }
2333 }
2334
2335 /**
2336 * Start preloading of resource data using this Resources object. Only
2337 * for use by the zygote process for loading common system resources.
2338 * {@hide}
2339 */
2340 public final void startPreloading() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002341 synchronized (sSync) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002342 if (sPreloaded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 throw new IllegalStateException("Resources already preloaded");
2344 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002345 sPreloaded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 mPreloading = true;
Dianne Hackborndde331c2012-08-03 14:01:57 -07002347 sPreloadedDensity = DisplayMetrics.DENSITY_DEVICE;
2348 mConfiguration.densityDpi = sPreloadedDensity;
2349 updateConfiguration(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 }
2351 }
2352
2353 /**
2354 * Called by zygote when it is done preloading resources, to change back
2355 * to normal Resources operation.
2356 */
2357 public final void finishPreloading() {
2358 if (mPreloading) {
2359 mPreloading = false;
2360 flushLayoutCache();
2361 }
2362 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002363
Romain Guy3b748a42013-04-17 18:54:38 -07002364 /**
2365 * @hide
2366 */
Alan Viverette52b999f2014-03-24 18:00:26 -07002367 public LongSparseArray<ConstantState> getPreloadedDrawables() {
Romain Guy3b748a42013-04-17 18:54:38 -07002368 return sPreloadedDrawables[0];
2369 }
2370
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002371 private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2372 int resourceId, String name) {
2373 // We allow preloading of resources even if they vary by font scale (which
2374 // doesn't impact resource selection) or density (which we handle specially by
2375 // simply turning off all preloading), as well as any other configs specified
2376 // by the caller.
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002377 if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002378 ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002379 String resName;
2380 try {
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002381 resName = getResourceName(resourceId);
Dianne Hackborndde331c2012-08-03 14:01:57 -07002382 } catch (NotFoundException e) {
2383 resName = "?";
2384 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002385 // This should never happen in production, so we should log a
2386 // warning even if we're not debugging.
Dianne Hackborndde331c2012-08-03 14:01:57 -07002387 Log.w(TAG, "Preloaded " + name + " resource #0x"
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002388 + Integer.toHexString(resourceId)
Dianne Hackborndde331c2012-08-03 14:01:57 -07002389 + " (" + resName + ") that varies with configuration!!");
2390 return false;
2391 }
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -07002392 if (TRACE_FOR_PRELOAD) {
2393 String resName;
2394 try {
2395 resName = getResourceName(resourceId);
2396 } catch (NotFoundException e) {
2397 resName = "?";
2398 }
2399 Log.w(TAG, "Preloading " + name + " resource #0x"
2400 + Integer.toHexString(resourceId)
2401 + " (" + resName + ")");
2402 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002403 return true;
2404 }
2405
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002406 /*package*/ Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 if (TRACE_FOR_PRELOAD) {
2408 // Log only framework resources
2409 if ((id >>> 24) == 0x1) {
2410 final String name = getResourceName(id);
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002411 if (name != null) {
2412 Log.d("PreloadDrawable", name);
2413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 }
2415 }
2416
Alan Viverette52b999f2014-03-24 18:00:26 -07002417 final boolean isColorDrawable;
Alan Viverette75257ce2014-05-22 19:31:38 -07002418 final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches;
Alan Viverette52b999f2014-03-24 18:00:26 -07002419 final long key;
2420 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2421 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
Masanori Oginoc7d9d272010-07-10 12:10:41 +09002422 isColorDrawable = true;
Alan Viverette52b999f2014-03-24 18:00:26 -07002423 caches = mColorDrawableCache;
2424 key = value.data;
2425 } else {
2426 isColorDrawable = false;
2427 caches = mDrawableCache;
2428 key = (((long) value.assetCookie) << 32) | value.data;
Masanori Oginoc7d9d272010-07-10 12:10:41 +09002429 }
Romain Guy5f49c302012-09-06 16:33:31 -07002430
Alan Viverette52b999f2014-03-24 18:00:26 -07002431 // First, check whether we have a cached version of this drawable
Alan Viveretteb6f91522014-06-03 12:52:25 -07002432 // that was inflated against the specified theme.
Alan Viverette52b999f2014-03-24 18:00:26 -07002433 if (!mPreloading) {
2434 final Drawable cachedDrawable = getCachedDrawable(caches, key, theme);
2435 if (cachedDrawable != null) {
2436 return cachedDrawable;
2437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002439
2440 // Next, check preloaded drawables. These are unthemed but may have
2441 // themeable attributes.
2442 final ConstantState cs;
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002443 if (isColorDrawable) {
2444 cs = sPreloadedColorDrawables.get(key);
2445 } else {
2446 cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2447 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002448
2449 final Drawable dr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 if (cs != null) {
Alan Viverette727cae12014-10-07 15:08:47 -07002451 final Drawable clonedDr = cs.newDrawable(this);
2452 if (theme != null) {
2453 dr = clonedDr.mutate();
2454 dr.applyTheme(theme);
2455 dr.clearMutated();
2456 } else {
2457 dr = clonedDr;
2458 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002459 } else if (isColorDrawable) {
2460 dr = new ColorDrawable(value.data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 } else {
Alan Viverette52b999f2014-03-24 18:00:26 -07002462 dr = loadDrawableForCookie(value, id, theme);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
Alan Viveretteb6f91522014-06-03 12:52:25 -07002465 // If we were able to obtain a drawable, store it in the appropriate
2466 // cache (either preload or themed).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 if (dr != null) {
2468 dr.setChangingConfigurations(value.changingConfigurations);
Alan Viverette52b999f2014-03-24 18:00:26 -07002469 cacheDrawable(value, theme, isColorDrawable, caches, key, dr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
2471
2472 return dr;
2473 }
2474
Alan Viverette52b999f2014-03-24 18:00:26 -07002475 private void cacheDrawable(TypedValue value, Theme theme, boolean isColorDrawable,
Alan Viverette75257ce2014-05-22 19:31:38 -07002476 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches,
2477 long key, Drawable dr) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002478 final ConstantState cs = dr.getConstantState();
2479 if (cs == null) {
2480 return;
2481 }
2482
Alan Viverette52b999f2014-03-24 18:00:26 -07002483 if (mPreloading) {
2484 // Preloaded drawables never have a theme, but may be themeable.
2485 final int changingConfigs = cs.getChangingConfigurations();
2486 if (isColorDrawable) {
2487 if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2488 sPreloadedColorDrawables.put(key, cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002490 } else {
2491 if (verifyPreloadConfig(
2492 changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2493 if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2494 // If this resource does not vary based on layout direction,
2495 // we can put it in all of the preload maps.
2496 sPreloadedDrawables[0].put(key, cs);
2497 sPreloadedDrawables[1].put(key, cs);
2498 } else {
2499 // Otherwise, only in the layout dir we loaded it for.
2500 sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 }
2503 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002504 } else {
2505 synchronized (mAccessLock) {
Alan Viverette75257ce2014-05-22 19:31:38 -07002506 final String themeKey = theme == null ? "" : theme.mKey;
2507 LongSparseArray<WeakReference<ConstantState>> themedCache = caches.get(themeKey);
2508 if (themedCache == null) {
Alan Viverette9267fda2014-12-08 12:20:01 -08002509 // Clean out the caches before we add more. This shouldn't
2510 // happen very often.
2511 pruneCaches(caches);
Alan Viverettea8636c92015-03-27 10:44:39 -07002512 themedCache = new LongSparseArray<>(1);
Alan Viverette75257ce2014-05-22 19:31:38 -07002513 caches.put(themeKey, themedCache);
2514 }
Alan Viverettea8636c92015-03-27 10:44:39 -07002515 themedCache.put(key, new WeakReference<>(cs));
Alan Viverette52b999f2014-03-24 18:00:26 -07002516 }
2517 }
2518 }
2519
2520 /**
Alan Viverette9267fda2014-12-08 12:20:01 -08002521 * Prunes empty caches from the cache map.
2522 *
2523 * @param caches The map of caches to prune.
2524 */
2525 private void pruneCaches(ArrayMap<String,
2526 LongSparseArray<WeakReference<ConstantState>>> caches) {
2527 final int N = caches.size();
2528 for (int i = N - 1; i >= 0; i--) {
Jeff Sharkeyc4ec5b62014-12-17 10:24:13 -08002529 final LongSparseArray<WeakReference<ConstantState>> cache = caches.valueAt(i);
Alan Viverette9267fda2014-12-08 12:20:01 -08002530 if (pruneCache(cache)) {
2531 caches.removeAt(i);
2532 }
2533 }
2534 }
2535
2536 /**
2537 * Prunes obsolete weak references from a cache, returning {@code true} if
2538 * the cache is empty and should be removed.
2539 *
2540 * @param cache The cache of weak references to prune.
2541 * @return {@code true} if the cache is empty and should be removed.
2542 */
2543 private boolean pruneCache(LongSparseArray<WeakReference<ConstantState>> cache) {
2544 final int N = cache.size();
2545 for (int i = N - 1; i >= 0; i--) {
2546 final WeakReference entry = cache.valueAt(i);
Alan Viveretted6ebb3a2015-01-05 11:09:29 -08002547 if (entry == null || entry.get() == null) {
Alan Viverette9267fda2014-12-08 12:20:01 -08002548 cache.removeAt(i);
2549 }
2550 }
2551 return cache.size() == 0;
2552 }
2553
2554 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07002555 * Loads a drawable from XML or resources stream.
2556 */
2557 private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2558 if (value.string == null) {
Alan Viverette0810b632014-05-01 14:42:56 -07002559 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002560 + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
Alan Viverette52b999f2014-03-24 18:00:26 -07002561 }
2562
2563 final String file = value.string.toString();
2564
2565 if (TRACE_FOR_MISS_PRELOAD) {
2566 // Log only framework resources
2567 if ((id >>> 24) == 0x1) {
2568 final String name = getResourceName(id);
2569 if (name != null) {
2570 Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2571 + ": " + name + " at " + file);
2572 }
2573 }
2574 }
2575
2576 if (DEBUG_LOAD) {
2577 Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2578 }
2579
2580 final Drawable dr;
2581
2582 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2583 try {
2584 if (file.endsWith(".xml")) {
2585 final XmlResourceParser rp = loadXmlResourceParser(
2586 file, id, value.assetCookie, "drawable");
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002587 dr = Drawable.createFromXml(this, rp, theme);
Alan Viverette52b999f2014-03-24 18:00:26 -07002588 rp.close();
2589 } else {
2590 final InputStream is = mAssets.openNonAsset(
2591 value.assetCookie, file, AssetManager.ACCESS_STREAMING);
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002592 dr = Drawable.createFromResourceStream(this, value, is, file, null);
Alan Viverette52b999f2014-03-24 18:00:26 -07002593 is.close();
2594 }
2595 } catch (Exception e) {
2596 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2597 final NotFoundException rnf = new NotFoundException(
2598 "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2599 rnf.initCause(e);
2600 throw rnf;
2601 }
2602 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2603
2604 return dr;
2605 }
2606
Alan Viverette75257ce2014-05-22 19:31:38 -07002607 private Drawable getCachedDrawable(
2608 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches,
2609 long key, Theme theme) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002610 synchronized (mAccessLock) {
Alan Viveretteb6f91522014-06-03 12:52:25 -07002611 final String themeKey = theme != null ? theme.mKey : "";
Alan Viverette52b999f2014-03-24 18:00:26 -07002612 final LongSparseArray<WeakReference<ConstantState>> themedCache = caches.get(themeKey);
2613 if (themedCache != null) {
2614 final Drawable themedDrawable = getCachedDrawableLocked(themedCache, key);
2615 if (themedDrawable != null) {
2616 return themedDrawable;
2617 }
2618 }
2619
2620 // No cached drawable, we'll need to create a new one.
2621 return null;
2622 }
2623 }
2624
2625 private ConstantState getConstantStateLocked(
2626 LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) {
2627 final WeakReference<ConstantState> wr = drawableCache.get(key);
2628 if (wr != null) { // we have the key
2629 final ConstantState entry = wr.get();
2630 if (entry != null) {
2631 //Log.i(TAG, "Returning cached drawable @ #" +
2632 // Integer.toHexString(((Integer)key).intValue())
2633 // + " in " + this + ": " + entry);
2634 return entry;
2635 } else { // our entry has been purged
2636 drawableCache.delete(key);
2637 }
2638 }
2639 return null;
2640 }
2641
2642 private Drawable getCachedDrawableLocked(
2643 LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) {
2644 final ConstantState entry = getConstantStateLocked(drawableCache, key);
2645 if (entry != null) {
2646 return entry.newDrawable(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 return null;
2649 }
2650
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002651 @Nullable
2652 ColorStateList loadColorStateList(TypedValue value, int id, Theme theme)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 throws NotFoundException {
2654 if (TRACE_FOR_PRELOAD) {
2655 // Log only framework resources
2656 if ((id >>> 24) == 0x1) {
2657 final String name = getResourceName(id);
2658 if (name != null) android.util.Log.d("PreloadColorStateList", name);
2659 }
2660 }
2661
Romain Guy5d911c32012-04-12 16:25:17 -07002662 final long key = (((long) value.assetCookie) << 32) | value.data;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663
2664 ColorStateList csl;
2665
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002666 // Handle inline color definitions.
2667 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2668 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
Alan Viverettee0f95f32015-04-01 13:10:18 -07002669 final android.content.res.ConstantState<ColorStateList> factory =
2670 sPreloadedColorStateLists.get(key);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002671 if (factory != null) {
2672 return factory.newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674
2675 csl = ColorStateList.valueOf(value.data);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 if (mPreloading) {
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002678 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2679 "color")) {
Alan Viverettee0f95f32015-04-01 13:10:18 -07002680 sPreloadedColorStateLists.put(key, csl.getConstantState());
Dianne Hackborndde331c2012-08-03 14:01:57 -07002681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683
2684 return csl;
2685 }
2686
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002687 final ConfigurationBoundResourceCache<ColorStateList> cache = mColorStateListCache;
2688
2689 csl = cache.get(key, theme);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (csl != null) {
2691 return csl;
2692 }
2693
Alan Viverettee0f95f32015-04-01 13:10:18 -07002694 final android.content.res.ConstantState<ColorStateList> factory =
2695 sPreloadedColorStateLists.get(key);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002696 if (factory != null) {
2697 csl = factory.newInstance(this, theme);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 }
2699
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002700 if (csl == null) {
2701 csl = loadColorStateListForCookie(value, id, theme);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
2703
2704 if (csl != null) {
2705 if (mPreloading) {
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002706 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2707 "color")) {
Alan Viverettee0f95f32015-04-01 13:10:18 -07002708 sPreloadedColorStateLists.put(key, csl.getConstantState());
Dianne Hackborndde331c2012-08-03 14:01:57 -07002709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 } else {
Alan Viverettee0f95f32015-04-01 13:10:18 -07002711 cache.put(key, theme, csl.getConstantState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 }
2714
2715 return csl;
2716 }
2717
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002718 private ColorStateList loadColorStateListForCookie(TypedValue value, int id, Theme theme) {
2719 if (value.string == null) {
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002720 throw new UnsupportedOperationException(
2721 "Can't convert to color state list: type=0x" + value.type);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002722 }
2723
2724 final String file = value.string.toString();
2725
2726 if (TRACE_FOR_MISS_PRELOAD) {
2727 // Log only framework resources
2728 if ((id >>> 24) == 0x1) {
2729 final String name = getResourceName(id);
2730 if (name != null) {
2731 Log.d(TAG, "Loading framework color state list #" + Integer.toHexString(id)
2732 + ": " + name + " at " + file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
2734 }
2735 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002736
2737 if (DEBUG_LOAD) {
2738 Log.v(TAG, "Loading color state list for cookie " + value.assetCookie + ": " + file);
2739 }
2740
2741 final ColorStateList csl;
2742
2743 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2744 if (file.endsWith(".xml")) {
2745 try {
2746 final XmlResourceParser rp = loadXmlResourceParser(
2747 file, id, value.assetCookie, "colorstatelist");
2748 csl = ColorStateList.createFromXml(this, rp, theme);
2749 rp.close();
2750 } catch (Exception e) {
2751 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2752 final NotFoundException rnf = new NotFoundException(
2753 "File " + file + " from color state list resource ID #0x"
2754 + Integer.toHexString(id));
2755 rnf.initCause(e);
2756 throw rnf;
2757 }
2758 } else {
2759 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2760 throw new NotFoundException(
2761 "File " + file + " from drawable resource ID #0x"
2762 + Integer.toHexString(id) + ": .xml extension required");
2763 }
2764 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2765
2766 return csl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 }
2768
2769 /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type)
2770 throws NotFoundException {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002771 synchronized (mAccessLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 TypedValue value = mTmpValue;
Dianne Hackborne5b50a62013-02-11 16:18:42 -08002773 if (value == null) {
2774 mTmpValue = value = new TypedValue();
2775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 getValue(id, value, true);
2777 if (value.type == TypedValue.TYPE_STRING) {
2778 return loadXmlResourceParser(value.string.toString(), id,
2779 value.assetCookie, type);
2780 }
2781 throw new NotFoundException(
2782 "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
2783 + Integer.toHexString(value.type) + " is not valid");
2784 }
2785 }
2786
2787 /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id,
2788 int assetCookie, String type) throws NotFoundException {
2789 if (id != 0) {
2790 try {
2791 // These may be compiled...
2792 synchronized (mCachedXmlBlockIds) {
2793 // First see if this block is in our cache.
2794 final int num = mCachedXmlBlockIds.length;
2795 for (int i=0; i<num; i++) {
2796 if (mCachedXmlBlockIds[i] == id) {
2797 //System.out.println("**** REUSING XML BLOCK! id="
2798 // + id + ", index=" + i);
2799 return mCachedXmlBlocks[i].newParser();
2800 }
2801 }
2802
2803 // Not in the cache, create a new block and put it at
2804 // the next slot in the cache.
2805 XmlBlock block = mAssets.openXmlBlockAsset(
2806 assetCookie, file);
2807 if (block != null) {
2808 int pos = mLastCachedXmlBlockIndex+1;
2809 if (pos >= num) pos = 0;
2810 mLastCachedXmlBlockIndex = pos;
2811 XmlBlock oldBlock = mCachedXmlBlocks[pos];
2812 if (oldBlock != null) {
2813 oldBlock.close();
2814 }
2815 mCachedXmlBlockIds[pos] = id;
2816 mCachedXmlBlocks[pos] = block;
2817 //System.out.println("**** CACHING NEW XML BLOCK! id="
2818 // + id + ", index=" + pos);
2819 return block.newParser();
2820 }
2821 }
2822 } catch (Exception e) {
2823 NotFoundException rnf = new NotFoundException(
2824 "File " + file + " from xml type " + type + " resource ID #0x"
2825 + Integer.toHexString(id));
2826 rnf.initCause(e);
2827 throw rnf;
2828 }
2829 }
2830
2831 throw new NotFoundException(
2832 "File " + file + " from xml type " + type + " resource ID #0x"
2833 + Integer.toHexString(id));
2834 }
2835
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002836 /**
2837 * Obtains styled attributes from the theme, if available, or unstyled
2838 * resources if the theme is null.
2839 *
2840 * @hide
2841 */
2842 public static TypedArray obtainAttributes(
2843 Resources res, Theme theme, AttributeSet set, int[] attrs) {
2844 if (theme == null) {
2845 return res.obtainAttributes(set, attrs);
2846 }
2847 return theme.obtainStyledAttributes(set, attrs, 0, 0);
2848 }
2849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 private Resources() {
2851 mAssets = AssetManager.getSystem();
2852 // NOTE: Intentionally leaving this uninitialized (all values set
2853 // to zero), so that anyone who tries to do something that requires
2854 // metrics will get a very wrong value.
2855 mConfiguration.setToDefaults();
2856 mMetrics.setToDefaults();
2857 updateConfiguration(null, null);
2858 mAssets.ensureStringBlocks();
2859 }
2860}