blob: a9150e88701f662db7e856e9980901bf0f89d58f [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
Alan Viverette45c4bbb2015-01-05 14:59:19 -080019import android.animation.Animator;
20import android.animation.StateListAnimator;
Tor Norbye7b9c9122013-05-30 16:48:33 -070021import android.annotation.AnimRes;
22import android.annotation.AnyRes;
23import android.annotation.ArrayRes;
Roozbeh Pournader47571c72015-09-01 14:07:04 -070024import android.annotation.AttrRes;
Tor Norbye7b9c9122013-05-30 16:48:33 -070025import android.annotation.BoolRes;
Roozbeh Pournader47571c72015-09-01 14:07:04 -070026import android.annotation.ColorInt;
Tor Norbye7b9c9122013-05-30 16:48:33 -070027import android.annotation.ColorRes;
28import android.annotation.DimenRes;
29import android.annotation.DrawableRes;
30import android.annotation.FractionRes;
31import android.annotation.IntegerRes;
32import android.annotation.LayoutRes;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080033import android.annotation.NonNull;
Alan Viverette3b5c4272014-05-20 13:20:42 -070034import android.annotation.Nullable;
Tor Norbye7b9c9122013-05-30 16:48:33 -070035import android.annotation.PluralsRes;
36import android.annotation.RawRes;
37import android.annotation.StringRes;
Roozbeh Pournader47571c72015-09-01 14:07:04 -070038import android.annotation.StyleRes;
39import android.annotation.StyleableRes;
Tor Norbye7b9c9122013-05-30 16:48:33 -070040import android.annotation.XmlRes;
Dianne Hackbornebff8f92011-05-12 18:07:47 -070041import android.content.pm.ActivityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.graphics.Movie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.graphics.drawable.ColorDrawable;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080044import android.graphics.drawable.Drawable;
Masanori Oginoc7d9d272010-07-10 12:10:41 +090045import android.graphics.drawable.Drawable.ConstantState;
Roozbeh Pournader47571c72015-09-01 14:07:04 -070046import android.graphics.drawable.DrawableInflater;
47import android.icu.text.PluralRules;
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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.util.AttributeSet;
52import android.util.DisplayMetrics;
Roozbeh Pournader47571c72015-09-01 14:07:04 -070053import android.util.LocaleList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import 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;
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -080059import android.util.Xml;
Alan Viverette45c4bbb2015-01-05 14:59:19 -080060import android.view.ViewDebug;
Siva Velusamy0d857b92015-04-22 10:23:56 -070061import android.view.ViewHierarchyEncoder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
Roozbeh Pournader47571c72015-09-01 14:07:04 -070063import com.android.internal.util.GrowingArrayUtils;
64import com.android.internal.util.XmlUtils;
65
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.IOException;
70import java.io.InputStream;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080071import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
73/**
74 * Class for accessing an application's resources. This sits on top of the
Scott Mainf4f05b82011-01-07 14:38:23 -080075 * asset manager of the application (accessible through {@link #getAssets}) and
76 * provides a high-level API for getting typed data from the assets.
77 *
78 * <p>The Android resource system keeps track of all non-code assets associated with an
79 * application. You can use this class to access your application's resources. You can generally
80 * acquire the {@link android.content.res.Resources} instance associated with your application
81 * with {@link android.content.Context#getResources getResources()}.</p>
82 *
83 * <p>The Android SDK tools compile your application's resources into the application binary
84 * at build time. To use a resource, you must install it correctly in the source tree (inside
85 * your project's {@code res/} directory) and build your application. As part of the build
86 * process, the SDK tools generate symbols for each resource, which you can use in your application
87 * code to access the resources.</p>
88 *
89 * <p>Using application resources makes it easy to update various characteristics of your
90 * application without modifying code, and&mdash;by providing sets of alternative
91 * resources&mdash;enables you to optimize your application for a variety of device configurations
92 * (such as for different languages and screen sizes). This is an important aspect of developing
93 * Android applications that are compatible on different types of devices.</p>
94 *
95 * <p>For more information about using resources, see the documentation about <a
96 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 */
98public class Resources {
99 static final String TAG = "Resources";
Alan Viverette562a6a82014-01-31 11:07:29 -0800100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final boolean DEBUG_LOAD = false;
102 private static final boolean DEBUG_CONFIG = false;
103 private static final boolean TRACE_FOR_PRELOAD = false;
Dianne Hackborn9b44aae2011-09-02 19:17:16 -0700104 private static final boolean TRACE_FOR_MISS_PRELOAD = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Alan Viverette562a6a82014-01-31 11:07:29 -0800106 private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
107 ActivityInfo.CONFIG_LAYOUT_DIRECTION);
108
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700109 private static final int ID_OTHER = 0x01000004;
110
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800111 private static final Object sSync = new Object();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 // Information about preloaded resources. Note that they are not
114 // protected by a lock, because while preloading in zygote we are all
115 // single-threaded, and after that these are immutable.
Alan Viverette52b999f2014-03-24 18:00:26 -0700116 private static final LongSparseArray<ConstantState>[] sPreloadedDrawables;
117 private static final LongSparseArray<ConstantState> sPreloadedColorDrawables
Alan Viverettea8636c92015-03-27 10:44:39 -0700118 = new LongSparseArray<>();
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -0800119 private static final LongSparseArray<android.content.res.ConstantState<ComplexColor>>
120 sPreloadedComplexColors = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700121
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700122 // Pool of TypedArrays targeted to this Resources object.
Alan Viverettea8636c92015-03-27 10:44:39 -0700123 final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700124
Alan Viveretteedc46642014-02-01 01:43:16 -0800125 // Used by BridgeResources in layoutlib
126 static Resources mSystem = null;
127
Dianne Hackborndde331c2012-08-03 14:01:57 -0700128 private static boolean sPreloaded;
Alan Viverette4d07bc92015-11-16 10:19:12 -0500129
130 /** Lock object used to protect access to caches and configuration. */
131 private final Object mAccessLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800133 // These are protected by mAccessLock.
Alan Viverette562a6a82014-01-31 11:07:29 -0800134 private final Configuration mTmpConfig = new Configuration();
Alan Viverettee54d2452015-05-06 10:41:43 -0700135 private final DrawableCache mDrawableCache = new DrawableCache(this);
136 private final DrawableCache mColorDrawableCache = new DrawableCache(this);
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -0800137 private final ConfigurationBoundResourceCache<ComplexColor> mComplexColorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700138 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700139 private final ConfigurationBoundResourceCache<Animator> mAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700140 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700141 private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700142 new ConfigurationBoundResourceCache<>(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400144 /** Used to inflate drawable objects from XML. */
145 private DrawableInflater mDrawableInflater;
146
Alan Viverette4d07bc92015-11-16 10:19:12 -0500147 /** Lock object used to protect access to {@link #mTmpValue}. */
148 private final Object mTmpValueLock = new Object();
149
150 /** Single-item pool used to minimize TypedValue allocations. */
Alan Viverette562a6a82014-01-31 11:07:29 -0800151 private TypedValue mTmpValue = new TypedValue();
Alan Viverette4d07bc92015-11-16 10:19:12 -0500152
Alan Viverette562a6a82014-01-31 11:07:29 -0800153 private boolean mPreloading;
154
Alan Viverette10979612016-01-06 15:27:35 -0500155 // Cyclical cache used for recently-accessed XML files.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private int mLastCachedXmlBlockIndex = -1;
Alan Viverette10979612016-01-06 15:27:35 -0500157 private final String[] mCachedXmlBlockFiles = new String[4];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4];
159
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700160 final AssetManager mAssets;
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400161 final ClassLoader mClassLoader;
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700162 final DisplayMetrics mMetrics = new DisplayMetrics();
163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 private final Configuration mConfiguration = new Configuration();
Raph Levien1f0945e2016-01-20 12:16:50 -0800165
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100166 private PluralRules mPluralRule;
Craig Mautner48d0d182013-06-11 07:53:06 -0700167
168 private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
Alan Viverette52b999f2014-03-24 18:00:26 -0700169
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700170 static {
171 sPreloadedDrawables = new LongSparseArray[2];
Alan Viverettea8636c92015-03-27 10:44:39 -0700172 sPreloadedDrawables[0] = new LongSparseArray<>();
173 sPreloadedDrawables[1] = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700174 }
175
Alan Viverette62599332014-04-01 14:57:39 -0700176 /**
177 * Returns the most appropriate default theme for the specified target SDK version.
Alan Viverette5effd7e2014-05-05 12:25:33 -0700178 * <ul>
179 * <li>Below API 11: Gingerbread
180 * <li>APIs 11 thru 14: Holo
181 * <li>APIs 14 thru XX: Device default dark
182 * <li>API XX and above: Device default light with dark action bar
183 * </ul>
Alan Viverette62599332014-04-01 14:57:39 -0700184 *
185 * @param curTheme The current theme, or 0 if not specified.
186 * @param targetSdkVersion The target SDK version.
187 * @return A theme resource identifier
188 * @hide
189 */
Alan Viverette5effd7e2014-05-05 12:25:33 -0700190 public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800191 return selectSystemTheme(curTheme, targetSdkVersion,
Alan Viverette5effd7e2014-05-05 12:25:33 -0700192 com.android.internal.R.style.Theme,
193 com.android.internal.R.style.Theme_Holo,
194 com.android.internal.R.style.Theme_DeviceDefault,
195 com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar);
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800196 }
Alan Viverette62599332014-04-01 14:57:39 -0700197
Alan Viverette5effd7e2014-05-05 12:25:33 -0700198 /** @hide */
199 public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo,
200 int dark, int deviceDefault) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800201 if (curTheme != 0) {
202 return curTheme;
203 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700204 if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) {
205 return orig;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800206 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700207 if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
208 return holo;
209 }
210 if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) {
211 return dark;
212 }
213 return deviceDefault;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800214 }
Alan Viverette62599332014-04-01 14:57:39 -0700215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 /**
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400217 * @return the inflater used to create drawable objects
218 * @hide Pending API finalization.
219 */
220 public final DrawableInflater getDrawableInflater() {
221 if (mDrawableInflater == null) {
222 mDrawableInflater = new DrawableInflater(this, mClassLoader);
223 }
224 return mDrawableInflater;
225 }
226
227 /**
Yigit Boyard422dc32014-09-25 12:23:35 -0700228 * Used by AnimatorInflater.
229 *
230 * @hide
231 */
232 public ConfigurationBoundResourceCache<Animator> getAnimatorCache() {
233 return mAnimatorCache;
234 }
235
236 /**
237 * Used by AnimatorInflater.
238 *
239 * @hide
240 */
241 public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
242 return mStateListAnimatorCache;
243 }
244
245 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 * This exception is thrown by the resource APIs when a requested resource
247 * can not be found.
248 */
249 public static class NotFoundException extends RuntimeException {
250 public NotFoundException() {
251 }
252
253 public NotFoundException(String name) {
254 super(name);
255 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500256
257 public NotFoundException(String name, Exception cause) {
258 super(name, cause);
259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 }
261
262 /**
263 * Create a new Resources object on top of an existing set of assets in an
264 * AssetManager.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800265 *
266 * @param assets Previously created AssetManager.
267 * @param metrics Current display metrics to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800269 * @param config Desired device configuration to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 * selecting/computing resource values (optional).
271 */
Romain Guy5d911c32012-04-12 16:25:17 -0700272 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400273 this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700274 }
275
276 /**
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700277 * Creates a new Resources object with CompatibilityInfo.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800278 *
279 * @param assets Previously created AssetManager.
280 * @param metrics Current display metrics to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700281 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800282 * @param config Desired device configuration to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700283 * selecting/computing resource values (optional).
Craig Mautner48d0d182013-06-11 07:53:06 -0700284 * @param compatInfo this resource's compatibility info. Must not be null.
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400285 * @param classLoader class loader for the package used to load custom
286 * resource classes, may be {@code null} to use system
287 * class loader
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700288 * @hide
289 */
Craig Mautner48d0d182013-06-11 07:53:06 -0700290 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400291 CompatibilityInfo compatInfo, @Nullable ClassLoader classLoader) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 mAssets = assets;
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400293 mClassLoader = classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 mMetrics.setToDefaults();
Adam Lesinski79a8ffe2013-09-19 20:33:15 -0700295 if (compatInfo != null) {
296 mCompatibilityInfo = compatInfo;
297 }
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700298 updateConfiguration(config, metrics);
299 assets.ensureStringBlocks();
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700300 }
301
302 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 * Return a global shared Resources object that provides access to only
Wale Ogunwale60454db2015-01-23 16:05:07 -0800304 * system resources (no application resources), and is not configured for
305 * the current screen (can not use dimension units, does not change based
306 * on orientation, etc).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 */
308 public static Resources getSystem() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800309 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 Resources ret = mSystem;
311 if (ret == null) {
312 ret = new Resources();
313 mSystem = ret;
314 }
315
316 return ret;
317 }
318 }
319
320 /**
321 * Return the string value associated with a particular resource ID. The
322 * returned object will be a String if this is a plain string; it will be
323 * some other type of CharSequence if it is styled.
324 * {@more}
325 *
326 * @param id The desired resource identifier, as generated by the aapt
327 * tool. This integer encodes the package, type, and resource
328 * entry. The value 0 is an invalid identifier.
329 *
330 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
331 *
332 * @return CharSequence The string data associated with the resource, plus
333 * possibly styled text information.
334 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700335 public CharSequence getText(@StringRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 CharSequence res = mAssets.getResourceText(id);
337 if (res != null) {
338 return res;
339 }
340 throw new NotFoundException("String resource ID #0x"
341 + Integer.toHexString(id));
342 }
343
344 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800345 * Returns the character sequence necessary for grammatically correct pluralization
346 * of the given resource ID for the given quantity.
347 * Note that the character sequence is selected based solely on grammatical necessity,
348 * and that such rules differ between languages. Do not assume you know which string
349 * will be returned for a given quantity. See
350 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
351 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700352 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 * @param id The desired resource identifier, as generated by the aapt
354 * tool. This integer encodes the package, type, and resource
355 * entry. The value 0 is an invalid identifier.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700356 * @param quantity The number used to get the correct string for the current language's
357 * plural rules.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 *
359 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
360 *
361 * @return CharSequence The string data associated with the resource, plus
362 * possibly styled text information.
363 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700364 public CharSequence getQuantityText(@PluralsRes int id, int quantity)
365 throws NotFoundException {
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100366 PluralRules rule = getPluralRule();
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700367 CharSequence res = mAssets.getResourceBagText(id,
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100368 attrForQuantityCode(rule.select(quantity)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 if (res != null) {
370 return res;
371 }
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700372 res = mAssets.getResourceBagText(id, ID_OTHER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 if (res != null) {
374 return res;
375 }
376 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
377 + " quantity=" + quantity
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100378 + " item=" + rule.select(quantity));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
380
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100381 private PluralRules getPluralRule() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800382 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 if (mPluralRule == null) {
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800384 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386 return mPluralRule;
387 }
388 }
389
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100390 private static int attrForQuantityCode(String quantityCode) {
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700391 switch (quantityCode) {
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100392 case PluralRules.KEYWORD_ZERO: return 0x01000005;
393 case PluralRules.KEYWORD_ONE: return 0x01000006;
394 case PluralRules.KEYWORD_TWO: return 0x01000007;
395 case PluralRules.KEYWORD_FEW: return 0x01000008;
396 case PluralRules.KEYWORD_MANY: return 0x01000009;
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700397 default: return ID_OTHER;
398 }
399 }
400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 /**
402 * Return the string value associated with a particular resource ID. It
403 * will be stripped of any styled text information.
404 * {@more}
405 *
406 * @param id The desired resource identifier, as generated by the aapt
407 * tool. This integer encodes the package, type, and resource
408 * entry. The value 0 is an invalid identifier.
409 *
410 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
411 *
412 * @return String The string data associated with the resource,
Alan Viveretteb4004df2015-04-29 16:55:42 -0700413 * stripped of styled text information.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 */
Alan Viveretteb4004df2015-04-29 16:55:42 -0700415 @NonNull
Tor Norbye7b9c9122013-05-30 16:48:33 -0700416 public String getString(@StringRes int id) throws NotFoundException {
Alan Viveretteb4004df2015-04-29 16:55:42 -0700417 final CharSequence res = getText(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 if (res != null) {
419 return res.toString();
420 }
421 throw new NotFoundException("String resource ID #0x"
422 + Integer.toHexString(id));
423 }
424
425
426 /**
427 * Return the string value associated with a particular resource ID,
428 * substituting the format arguments as defined in {@link java.util.Formatter}
429 * and {@link java.lang.String#format}. It will be stripped of any styled text
430 * information.
431 * {@more}
432 *
433 * @param id The desired resource identifier, as generated by the aapt
434 * tool. This integer encodes the package, type, and resource
435 * entry. The value 0 is an invalid identifier.
436 *
437 * @param formatArgs The format arguments that will be used for substitution.
438 *
439 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
440 *
441 * @return String The string data associated with the resource,
Alan Viveretteb4004df2015-04-29 16:55:42 -0700442 * stripped of styled text information.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 */
Alan Viveretteb4004df2015-04-29 16:55:42 -0700444 @NonNull
445 public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
446 final String raw = getString(id);
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800447 return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
449
450 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800451 * Formats the string necessary for grammatically correct pluralization
452 * of the given resource ID for the given quantity, using the given arguments.
453 * Note that the string is selected based solely on grammatical necessity,
454 * and that such rules differ between languages. Do not assume you know which string
455 * will be returned for a given quantity. See
456 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
457 * for more detail.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 *
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800459 * <p>Substitution of format arguments works as if using
460 * {@link java.util.Formatter} and {@link java.lang.String#format}.
461 * The resulting string will be stripped of any styled text information.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700462 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 * @param id The desired resource identifier, as generated by the aapt
464 * tool. This integer encodes the package, type, and resource
465 * entry. The value 0 is an invalid identifier.
466 * @param quantity The number used to get the correct string for the current language's
467 * plural rules.
468 * @param formatArgs The format arguments that will be used for substitution.
469 *
470 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
471 *
472 * @return String The string data associated with the resource,
473 * stripped of styled text information.
474 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700475 public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 throws NotFoundException {
477 String raw = getQuantityText(id, quantity).toString();
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800478 return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
480
481 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800482 * Returns the string necessary for grammatically correct pluralization
483 * of the given resource ID for the given quantity.
484 * Note that the string is selected based solely on grammatical necessity,
485 * and that such rules differ between languages. Do not assume you know which string
486 * will be returned for a given quantity. See
487 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
488 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700489 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 * @param id The desired resource identifier, as generated by the aapt
491 * tool. This integer encodes the package, type, and resource
492 * entry. The value 0 is an invalid identifier.
493 * @param quantity The number used to get the correct string for the current language's
494 * plural rules.
495 *
496 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
497 *
498 * @return String The string data associated with the resource,
499 * stripped of styled text information.
500 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700501 public String getQuantityString(@PluralsRes int id, int quantity)
502 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 return getQuantityText(id, quantity).toString();
504 }
505
506 /**
507 * Return the string value associated with a particular resource ID. The
508 * returned object will be a String if this is a plain string; it will be
509 * some other type of CharSequence if it is styled.
510 *
511 * @param id The desired resource identifier, as generated by the aapt
512 * tool. This integer encodes the package, type, and resource
513 * entry. The value 0 is an invalid identifier.
514 *
515 * @param def The default CharSequence to return.
516 *
517 * @return CharSequence The string data associated with the resource, plus
518 * possibly styled text information, or def if id is 0 or not found.
519 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700520 public CharSequence getText(@StringRes int id, CharSequence def) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
522 return res != null ? res : def;
523 }
524
525 /**
526 * Return the styled text array associated with a particular resource ID.
527 *
528 * @param id The desired resource identifier, as generated by the aapt
529 * tool. This integer encodes the package, type, and resource
530 * entry. The value 0 is an invalid identifier.
531 *
532 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
533 *
534 * @return The styled text array associated with the resource.
535 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700536 public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 CharSequence[] res = mAssets.getResourceTextArray(id);
538 if (res != null) {
539 return res;
540 }
541 throw new NotFoundException("Text array resource ID #0x"
542 + Integer.toHexString(id));
543 }
544
545 /**
546 * Return the string array associated with a particular resource ID.
547 *
548 * @param id The desired resource identifier, as generated by the aapt
549 * tool. This integer encodes the package, type, and resource
550 * entry. The value 0 is an invalid identifier.
551 *
552 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
553 *
554 * @return The string array associated with the resource.
555 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700556 public String[] getStringArray(@ArrayRes int id)
557 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 String[] res = mAssets.getResourceStringArray(id);
559 if (res != null) {
560 return res;
561 }
562 throw new NotFoundException("String array resource ID #0x"
563 + Integer.toHexString(id));
564 }
565
566 /**
567 * Return the int array associated with a particular resource ID.
568 *
569 * @param id The desired resource identifier, as generated by the aapt
570 * tool. This integer encodes the package, type, and resource
571 * entry. The value 0 is an invalid identifier.
572 *
573 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
574 *
575 * @return The int array associated with the resource.
576 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700577 public int[] getIntArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 int[] res = mAssets.getArrayIntResource(id);
579 if (res != null) {
580 return res;
581 }
582 throw new NotFoundException("Int array resource ID #0x"
583 + Integer.toHexString(id));
584 }
585
586 /**
587 * Return an array of heterogeneous values.
588 *
589 * @param id The desired resource identifier, as generated by the aapt
590 * tool. This integer encodes the package, type, and resource
591 * entry. The value 0 is an invalid identifier.
592 *
593 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
594 *
595 * @return Returns a TypedArray holding an array of the array values.
596 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
597 * when done with it.
598 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700599 public TypedArray obtainTypedArray(@ArrayRes int id)
600 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 int len = mAssets.getArraySize(id);
602 if (len < 0) {
603 throw new NotFoundException("Array resource ID #0x"
604 + Integer.toHexString(id));
605 }
606
Alan Viverette52b999f2014-03-24 18:00:26 -0700607 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 array.mLength = mAssets.retrieveArray(id, array.mData);
609 array.mIndices[0] = 0;
610
611 return array;
612 }
613
614 /**
615 * Retrieve a dimensional for a particular resource ID. Unit
616 * conversions are based on the current {@link DisplayMetrics} associated
617 * with the resources.
618 *
619 * @param id The desired resource identifier, as generated by the aapt
620 * tool. This integer encodes the package, type, and resource
621 * entry. The value 0 is an invalid identifier.
622 *
623 * @return Resource dimension value multiplied by the appropriate
624 * metric.
625 *
626 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
627 *
628 * @see #getDimensionPixelOffset
629 * @see #getDimensionPixelSize
630 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700631 public float getDimension(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500632 final TypedValue value = obtainTempTypedValue(id);
633 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 if (value.type == TypedValue.TYPE_DIMENSION) {
635 return TypedValue.complexToDimension(value.data, mMetrics);
636 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500637 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
638 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
639 } finally {
640 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642 }
643
644 /**
645 * Retrieve a dimensional for a particular resource ID for use
646 * as an offset in raw pixels. This is the same as
647 * {@link #getDimension}, except the returned value is converted to
648 * integer pixels for you. An offset conversion involves simply
649 * truncating the base value to an integer.
650 *
651 * @param id The desired resource identifier, as generated by the aapt
652 * tool. This integer encodes the package, type, and resource
653 * entry. The value 0 is an invalid identifier.
654 *
655 * @return Resource dimension value multiplied by the appropriate
656 * metric and truncated to integer pixels.
657 *
658 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
659 *
660 * @see #getDimension
661 * @see #getDimensionPixelSize
662 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700663 public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500664 final TypedValue value = obtainTempTypedValue(id);
665 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 if (value.type == TypedValue.TYPE_DIMENSION) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500667 return TypedValue.complexToDimensionPixelOffset(value.data, mMetrics);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500669 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
670 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
671 } finally {
672 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674 }
675
676 /**
677 * Retrieve a dimensional for a particular resource ID for use
678 * as a size in raw pixels. This is the same as
679 * {@link #getDimension}, except the returned value is converted to
680 * integer pixels for use as a size. A size conversion involves
681 * rounding the base value, and ensuring that a non-zero base value
682 * is at least one pixel in size.
683 *
684 * @param id The desired resource identifier, as generated by the aapt
685 * tool. This integer encodes the package, type, and resource
686 * entry. The value 0 is an invalid identifier.
687 *
688 * @return Resource dimension value multiplied by the appropriate
689 * metric and truncated to integer pixels.
690 *
691 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
692 *
693 * @see #getDimension
694 * @see #getDimensionPixelOffset
695 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700696 public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500697 final TypedValue value = obtainTempTypedValue(id);
698 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 if (value.type == TypedValue.TYPE_DIMENSION) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500700 return TypedValue.complexToDimensionPixelSize(value.data, mMetrics);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500702 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
703 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
704 } finally {
705 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707 }
708
709 /**
710 * Retrieve a fractional unit for a particular resource ID.
711 *
712 * @param id The desired resource identifier, as generated by the aapt
713 * tool. This integer encodes the package, type, and resource
714 * entry. The value 0 is an invalid identifier.
715 * @param base The base value of this fraction. In other words, a
716 * standard fraction is multiplied by this value.
717 * @param pbase The parent base value of this fraction. In other
718 * words, a parent fraction (nn%p) is multiplied by this
719 * value.
720 *
721 * @return Attribute fractional value multiplied by the appropriate
722 * base value.
723 *
724 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
725 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700726 public float getFraction(@FractionRes int id, int base, int pbase) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500727 final TypedValue value = obtainTempTypedValue(id);
728 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (value.type == TypedValue.TYPE_FRACTION) {
730 return TypedValue.complexToFraction(value.data, base, pbase);
731 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500732 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
733 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
734 } finally {
735 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737 }
738
739 /**
740 * Return a drawable object associated with a particular resource ID.
741 * Various types of objects will be returned depending on the underlying
742 * resource -- for example, a solid color, PNG image, scalable image, etc.
743 * The Drawable API hides these implementation details.
Dianne Hackbornfb5c3db2012-05-18 15:24:24 -0700744 *
745 * <p class="note"><strong>Note:</strong> Prior to
746 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
747 * would not correctly retrieve the final configuration density when
748 * the resource ID passed here is an alias to another Drawable resource.
749 * This means that if the density configuration of the alias resource
750 * is different than the actual resource, the density of the returned
751 * Drawable would be incorrect, resulting in bad scaling. To work
752 * around this, you can instead retrieve the Drawable through
753 * {@link TypedArray#getDrawable TypedArray.getDrawable}. Use
754 * {@link android.content.Context#obtainStyledAttributes(int[])
755 * Context.obtainStyledAttributes} with
756 * an array containing the resource ID of interest to create the TypedArray.</p>
757 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700758 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
759 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
760 * or {@link #getDrawable(int, Theme)} passing the desired theme.</p>
761 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 * @param id The desired resource identifier, as generated by the aapt
763 * tool. This integer encodes the package, type, and resource
764 * entry. The value 0 is an invalid identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 * @return Drawable An object that can be used to draw this resource.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800766 * @throws NotFoundException Throws NotFoundException if the given ID does
767 * not exist.
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700768 * @see #getDrawable(int, Theme)
Alan Viverettec10e3962014-12-02 14:58:08 -0800769 * @deprecated Use {@link #getDrawable(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 */
Alan Viverettec10e3962014-12-02 14:58:08 -0800771 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700772 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette34a14f962014-08-15 16:13:15 -0700773 final Drawable d = getDrawable(id, null);
Alan Viverette7e0aaae2014-11-24 11:27:09 -0800774 if (d != null && d.canApplyTheme()) {
Alan Viverette34a14f962014-08-15 16:13:15 -0700775 Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
776 + "attributes! Consider using Resources.getDrawable(int, Theme) or "
777 + "Context.getDrawable(int).", new RuntimeException());
778 }
779 return d;
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800780 }
781
782 /**
783 * Return a drawable object associated with a particular resource ID and
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700784 * styled for the specified theme. Various types of objects will be
785 * returned depending on the underlying resource -- for example, a solid
786 * color, PNG image, scalable image, etc.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800787 *
788 * @param id The desired resource identifier, as generated by the aapt
789 * tool. This integer encodes the package, type, and resource
790 * entry. The value 0 is an invalid identifier.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700791 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800792 * @return Drawable An object that can be used to draw this resource.
793 * @throws NotFoundException Throws NotFoundException if the given ID does
794 * not exist.
795 */
Alan Viverette4d07bc92015-11-16 10:19:12 -0500796 public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
797 throws NotFoundException {
798 final TypedValue value = obtainTempTypedValue(id);
799 try {
800 return loadDrawable(value, id, theme);
801 } finally {
802 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804 }
805
806 /**
Kenny Root55fc8502010-10-28 14:47:01 -0700807 * Return a drawable object associated with a particular resource ID for the
808 * given screen density in DPI. This will set the drawable's density to be
809 * the device's density multiplied by the ratio of actual drawable density
810 * to requested density. This allows the drawable to be scaled up to the
811 * correct size if needed. Various types of objects will be returned
812 * depending on the underlying resource -- for example, a solid color, PNG
813 * image, scalable image, etc. The Drawable API hides these implementation
814 * details.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800815 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700816 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
817 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
818 * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired
819 * theme.</p>
820 *
Kenny Root55fc8502010-10-28 14:47:01 -0700821 * @param id The desired resource identifier, as generated by the aapt tool.
822 * This integer encodes the package, type, and resource entry.
823 * The value 0 is an invalid identifier.
824 * @param density the desired screen density indicated by the resource as
825 * found in {@link DisplayMetrics}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800826 * @return Drawable An object that can be used to draw this resource.
Kenny Root55fc8502010-10-28 14:47:01 -0700827 * @throws NotFoundException Throws NotFoundException if the given ID does
828 * not exist.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800829 * @see #getDrawableForDensity(int, int, Theme)
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800830 * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead.
Kenny Root55fc8502010-10-28 14:47:01 -0700831 */
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800832 @Deprecated
Alan Viverette4d07bc92015-11-16 10:19:12 -0500833 public Drawable getDrawableForDensity(@DrawableRes int id, int density)
834 throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800835 return getDrawableForDensity(id, density, null);
836 }
837
838 /**
839 * Return a drawable object associated with a particular resource ID for the
840 * given screen density in DPI and styled for the specified theme.
841 *
842 * @param id The desired resource identifier, as generated by the aapt tool.
843 * This integer encodes the package, type, and resource entry.
844 * The value 0 is an invalid identifier.
845 * @param density The desired screen density indicated by the resource as
846 * found in {@link DisplayMetrics}.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700847 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800848 * @return Drawable An object that can be used to draw this resource.
849 * @throws NotFoundException Throws NotFoundException if the given ID does
850 * not exist.
851 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700852 public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500853 final TypedValue value = obtainTempTypedValue(id);
854 try {
Kenny Root55fc8502010-10-28 14:47:01 -0700855 getValueForDensity(id, density, value, true);
856
Alan Viverette7941a7f2016-01-06 11:11:53 -0500857 // If the drawable's XML lives in our current density qualifier,
858 // it's okay to use a scaled version from the cache. Otherwise, we
859 // need to actually load the drawable from XML.
860 final boolean useCache = value.density == mMetrics.densityDpi;
861
Kenny Root55fc8502010-10-28 14:47:01 -0700862 /*
863 * Pretend the requested density is actually the display density. If
864 * the drawable returned is not the requested density, then force it
865 * to be scaled later by dividing its density by the ratio of
866 * requested density to actual device density. Drawables that have
867 * undefined density or no density don't need to be handled here.
868 */
869 if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
870 if (value.density == density) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700871 value.density = mMetrics.densityDpi;
Kenny Root55fc8502010-10-28 14:47:01 -0700872 } else {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700873 value.density = (value.density * mMetrics.densityDpi) / density;
Kenny Root55fc8502010-10-28 14:47:01 -0700874 }
875 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800876
Alan Viverette7941a7f2016-01-06 11:11:53 -0500877 return loadDrawable(value, id, theme, useCache);
Alan Viverette4d07bc92015-11-16 10:19:12 -0500878 } finally {
879 releaseTempTypedValue(value);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800880 }
Kenny Root55fc8502010-10-28 14:47:01 -0700881 }
882
883 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 * Return a movie object associated with the particular resource ID.
885 * @param id The desired resource identifier, as generated by the aapt
886 * tool. This integer encodes the package, type, and resource
887 * entry. The value 0 is an invalid identifier.
888 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
889 *
890 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700891 public Movie getMovie(@RawRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 InputStream is = openRawResource(id);
893 Movie movie = Movie.decodeStream(is);
894 try {
895 is.close();
896 }
897 catch (java.io.IOException e) {
898 // don't care, since the return value is valid
899 }
900 return movie;
901 }
902
903 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800904 * Returns a color integer associated with a particular resource ID. If the
905 * resource holds a complex {@link ColorStateList}, then the default color
906 * from the set is returned.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 *
908 * @param id The desired resource identifier, as generated by the aapt
909 * tool. This integer encodes the package, type, and resource
910 * entry. The value 0 is an invalid identifier.
911 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800912 * @throws NotFoundException Throws NotFoundException if the given ID does
913 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800915 * @return A single color value in the form 0xAARRGGBB.
916 * @deprecated Use {@link #getColor(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 */
Tor Norbye80756e32015-03-02 09:39:27 -0800918 @ColorInt
Alan Viverette4a357cd2015-03-18 18:37:18 -0700919 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700920 public int getColor(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800921 return getColor(id, null);
922 }
923
924 /**
925 * Returns a themed color integer associated with a particular resource ID.
926 * If the resource holds a complex {@link ColorStateList}, then the default
927 * color from the set is returned.
928 *
929 * @param id The desired resource identifier, as generated by the aapt
930 * tool. This integer encodes the package, type, and resource
931 * entry. The value 0 is an invalid identifier.
932 * @param theme The theme used to style the color attributes, may be
933 * {@code null}.
934 *
935 * @throws NotFoundException Throws NotFoundException if the given ID does
936 * not exist.
937 *
938 * @return A single color value in the form 0xAARRGGBB.
939 */
Tor Norbye80756e32015-03-02 09:39:27 -0800940 @ColorInt
Tor Norbye7b9c9122013-05-30 16:48:33 -0700941 public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500942 final TypedValue value = obtainTempTypedValue(id);
943 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800945 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 return value.data;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800947 } else if (value.type != TypedValue.TYPE_STRING) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500948 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
949 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800951
Alan Viverette4d07bc92015-11-16 10:19:12 -0500952 final ColorStateList csl = loadColorStateList(value, id, theme);
953 return csl.getDefaultColor();
954 } finally {
955 releaseTempTypedValue(value);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958
959 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800960 * Returns a color state list associated with a particular resource ID. The
961 * resource may contain either a single raw color value or a complex
962 * {@link ColorStateList} holding multiple possible colors.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 *
964 * @param id The desired resource identifier of a {@link ColorStateList},
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800965 * as generated by the aapt tool. This integer encodes the
966 * package, type, and resource entry. The value 0 is an invalid
967 * identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800969 * @throws NotFoundException Throws NotFoundException if the given ID does
970 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800972 * @return A ColorStateList object containing either a single solid color
973 * or multiple colors that can be selected based on a state.
974 * @deprecated Use {@link #getColorStateList(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 */
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800976 @Nullable
Alan Viverette4a357cd2015-03-18 18:37:18 -0700977 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700978 public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800979 final ColorStateList csl = getColorStateList(id, null);
980 if (csl != null && csl.canApplyTheme()) {
981 Log.w(TAG, "ColorStateList " + getResourceName(id) + " has "
982 + "unresolved theme attributes! Consider using "
983 + "Resources.getColorStateList(int, Theme) or "
984 + "Context.getColorStateList(int).", new RuntimeException());
985 }
986 return csl;
987 }
988
989 /**
990 * Returns a themed color state list associated with a particular resource
991 * ID. The resource may contain either a single raw color value or a
992 * complex {@link ColorStateList} holding multiple possible colors.
993 *
994 * @param id The desired resource identifier of a {@link ColorStateList},
995 * as generated by the aapt tool. This integer encodes the
996 * package, type, and resource entry. The value 0 is an invalid
997 * identifier.
998 * @param theme The theme used to style the color attributes, may be
999 * {@code null}.
1000 *
1001 * @throws NotFoundException Throws NotFoundException if the given ID does
1002 * not exist.
1003 *
1004 * @return A themed ColorStateList object containing either a single solid
1005 * color or multiple colors that can be selected based on a state.
1006 */
1007 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -07001008 public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme)
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001009 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001010 final TypedValue value = obtainTempTypedValue(id);
1011 try {
1012 return loadColorStateList(value, id, theme);
1013 } finally {
1014 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
1016 }
1017
1018 /**
1019 * Return a boolean associated with a particular resource ID. This can be
1020 * used with any integral resource value, and will return true if it is
1021 * non-zero.
1022 *
1023 * @param id The desired resource identifier, as generated by the aapt
1024 * tool. This integer encodes the package, type, and resource
1025 * entry. The value 0 is an invalid identifier.
1026 *
1027 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1028 *
1029 * @return Returns the boolean value contained in the resource.
1030 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001031 public boolean getBoolean(@BoolRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001032 final TypedValue value = obtainTempTypedValue(id);
1033 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette4d07bc92015-11-16 10:19:12 -05001035 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 return value.data != 0;
1037 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001038 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1039 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1040 } finally {
1041 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
1044
1045 /**
1046 * Return an integer associated with a particular resource ID.
1047 *
1048 * @param id The desired resource identifier, as generated by the aapt
1049 * tool. This integer encodes the package, type, and resource
1050 * entry. The value 0 is an invalid identifier.
1051 *
1052 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1053 *
1054 * @return Returns the integer value contained in the resource.
1055 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001056 public int getInteger(@IntegerRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001057 final TypedValue value = obtainTempTypedValue(id);
1058 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette4d07bc92015-11-16 10:19:12 -05001060 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 return value.data;
1062 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001063 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1064 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1065 } finally {
1066 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 }
1069
1070 /**
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001071 * Retrieve a floating-point value for a particular resource ID.
1072 *
1073 * @param id The desired resource identifier, as generated by the aapt
1074 * tool. This integer encodes the package, type, and resource
1075 * entry. The value 0 is an invalid identifier.
1076 *
1077 * @return Returns the floating-point value contained in the resource.
1078 *
1079 * @throws NotFoundException Throws NotFoundException if the given ID does
1080 * not exist or is not a floating-point value.
1081 * @hide Pending API council approval.
1082 */
1083 public float getFloat(int id) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001084 final TypedValue value = obtainTempTypedValue(id);
1085 try {
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001086 if (value.type == TypedValue.TYPE_FLOAT) {
1087 return value.getFloat();
1088 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001089 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1090 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1091 } finally {
1092 releaseTempTypedValue(value);
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001093 }
1094 }
1095
1096 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * Return an XmlResourceParser through which you can read a view layout
1098 * description for the given resource ID. This parser has limited
1099 * functionality -- in particular, you can't change its input, and only
1100 * the high-level events are available.
1101 *
1102 * <p>This function is really a simple wrapper for calling
1103 * {@link #getXml} with a layout resource.
1104 *
1105 * @param id The desired resource identifier, as generated by the aapt
1106 * tool. This integer encodes the package, type, and resource
1107 * entry. The value 0 is an invalid identifier.
1108 *
1109 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1110 *
1111 * @return A new parser object through which you can read
1112 * the XML data.
1113 *
1114 * @see #getXml
1115 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001116 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 return loadXmlResourceParser(id, "layout");
1118 }
1119
1120 /**
1121 * Return an XmlResourceParser through which you can read an animation
1122 * description for the given resource ID. This parser has limited
1123 * functionality -- in particular, you can't change its input, and only
1124 * the high-level events are available.
1125 *
1126 * <p>This function is really a simple wrapper for calling
1127 * {@link #getXml} with an animation resource.
1128 *
1129 * @param id The desired resource identifier, as generated by the aapt
1130 * tool. This integer encodes the package, type, and resource
1131 * entry. The value 0 is an invalid identifier.
1132 *
1133 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1134 *
1135 * @return A new parser object through which you can read
1136 * the XML data.
1137 *
1138 * @see #getXml
1139 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001140 public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 return loadXmlResourceParser(id, "anim");
1142 }
1143
1144 /**
1145 * Return an XmlResourceParser through which you can read a generic XML
1146 * resource for the given resource ID.
1147 *
1148 * <p>The XmlPullParser implementation returned here has some limited
1149 * functionality. In particular, you can't change its input, and only
1150 * high-level parsing events are available (since the document was
1151 * pre-parsed for you at build time, which involved merging text and
1152 * stripping comments).
1153 *
1154 * @param id The desired resource identifier, as generated by the aapt
1155 * tool. This integer encodes the package, type, and resource
1156 * entry. The value 0 is an invalid identifier.
1157 *
1158 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1159 *
1160 * @return A new parser object through which you can read
1161 * the XML data.
1162 *
1163 * @see android.util.AttributeSet
1164 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001165 public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 return loadXmlResourceParser(id, "xml");
1167 }
1168
1169 /**
1170 * Open a data stream for reading a raw resource. This can only be used
1171 * with resources whose value is the name of an asset files -- that is, it can be
1172 * used to open drawable, sound, and raw resources; it will fail on string
1173 * and color resources.
1174 *
1175 * @param id The resource identifier to open, as generated by the appt
1176 * tool.
1177 *
1178 * @return InputStream Access to the resource data.
1179 *
1180 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1181 *
1182 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001183 public InputStream openRawResource(@RawRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001184 final TypedValue value = obtainTempTypedValue();
1185 try {
1186 return openRawResource(id, value);
1187 } finally {
1188 releaseTempTypedValue(value);
1189 }
1190 }
1191
1192 /**
1193 * Returns a TypedValue populated with data for the specified resource ID
1194 * that's suitable for temporary use. The obtained TypedValue should be
1195 * released using {@link #releaseTempTypedValue(TypedValue)}.
1196 *
1197 * @param id the resource ID for which data should be obtained
1198 * @return a populated typed value suitable for temporary use
1199 */
1200 private TypedValue obtainTempTypedValue(@AnyRes int id) {
1201 final TypedValue value = obtainTempTypedValue();
1202 getValue(id, value, true);
1203 return value;
1204 }
1205
1206 /**
1207 * Returns a TypedValue suitable for temporary use. The obtained TypedValue
1208 * should be released using {@link #releaseTempTypedValue(TypedValue)}.
1209 *
1210 * @return a typed value suitable for temporary use
1211 */
1212 private TypedValue obtainTempTypedValue() {
1213 TypedValue tmpValue = null;
1214 synchronized (mTmpValueLock) {
1215 if (mTmpValue != null) {
1216 tmpValue = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001217 mTmpValue = null;
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001220 if (tmpValue == null) {
1221 return new TypedValue();
1222 }
1223 return tmpValue;
1224 }
1225
1226 /**
1227 * Returns a TypedValue to the pool. After calling this method, the
1228 * specified TypedValue should no longer be accessed.
1229 *
1230 * @param value the typed value to return to the pool
1231 */
1232 private void releaseTempTypedValue(TypedValue value) {
1233 synchronized (mTmpValueLock) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001234 if (mTmpValue == null) {
1235 mTmpValue = value;
1236 }
1237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 }
1239
1240 /**
1241 * Open a data stream for reading a raw resource. This can only be used
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001242 * 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 -08001243 * used to open drawable, sound, and raw resources; it will fail on string
1244 * and color resources.
1245 *
1246 * @param id The resource identifier to open, as generated by the appt tool.
1247 * @param value The TypedValue object to hold the resource information.
1248 *
1249 * @return InputStream Access to the resource data.
1250 *
1251 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001253 public InputStream openRawResource(@RawRes int id, TypedValue value)
1254 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 getValue(id, value, true);
1256
1257 try {
1258 return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1259 AssetManager.ACCESS_STREAMING);
1260 } catch (Exception e) {
1261 NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1262 " from drawable resource ID #0x" + Integer.toHexString(id));
1263 rnf.initCause(e);
1264 throw rnf;
1265 }
1266 }
1267
1268 /**
1269 * Open a file descriptor for reading a raw resource. This can only be used
1270 * with resources whose value is the name of an asset files -- that is, it can be
1271 * used to open drawable, sound, and raw resources; it will fail on string
1272 * and color resources.
1273 *
1274 * <p>This function only works for resources that are stored in the package
1275 * as uncompressed data, which typically includes things like mp3 files
1276 * and png images.
1277 *
1278 * @param id The resource identifier to open, as generated by the appt
1279 * tool.
1280 *
1281 * @return AssetFileDescriptor A new file descriptor you can use to read
1282 * the resource. This includes the file descriptor itself, as well as the
1283 * offset and length of data where the resource appears in the file. A
1284 * null is returned if the file exists but is compressed.
1285 *
1286 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1287 *
1288 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001289 public AssetFileDescriptor openRawResourceFd(@RawRes int id)
1290 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001291 final TypedValue value = obtainTempTypedValue(id);
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001292 try {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001293 return mAssets.openNonAssetFd(value.assetCookie, value.string.toString());
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001294 } catch (Exception e) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001295 throw new NotFoundException("File " + value.string.toString() + " from drawable "
1296 + "resource ID #0x" + Integer.toHexString(id), e);
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001297 } finally {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001298 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 }
1301
1302 /**
1303 * Return the raw data associated with a particular resource ID.
1304 *
1305 * @param id The desired resource identifier, as generated by the aapt
1306 * tool. This integer encodes the package, type, and resource
1307 * entry. The value 0 is an invalid identifier.
1308 * @param outValue Object in which to place the resource data.
1309 * @param resolveRefs If true, a resource that is a reference to another
1310 * resource will be followed so that you receive the
1311 * actual final resource data. If false, the TypedValue
1312 * will be filled in with the reference itself.
1313 *
1314 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1315 *
1316 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001317 public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001319 boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 if (found) {
1321 return;
1322 }
1323 throw new NotFoundException("Resource ID #0x"
1324 + Integer.toHexString(id));
1325 }
1326
1327 /**
Kenny Root55fc8502010-10-28 14:47:01 -07001328 * Get the raw value associated with a resource with associated density.
1329 *
1330 * @param id resource identifier
1331 * @param density density in DPI
1332 * @param resolveRefs If true, a resource that is a reference to another
1333 * resource will be followed so that you receive the actual final
1334 * resource data. If false, the TypedValue will be filled in with
1335 * the reference itself.
1336 * @throws NotFoundException Throws NotFoundException if the given ID does
1337 * not exist.
1338 * @see #getValue(String, TypedValue, boolean)
Kenny Root55fc8502010-10-28 14:47:01 -07001339 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001340 public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
1341 boolean resolveRefs) throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001342 boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1343 if (found) {
1344 return;
1345 }
1346 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1347 }
1348
1349 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 * Return the raw data associated with a particular resource ID.
1351 * See getIdentifier() for information on how names are mapped to resource
1352 * IDs, and getString(int) for information on how string resources are
1353 * retrieved.
1354 *
1355 * <p>Note: use of this function is discouraged. It is much more
1356 * efficient to retrieve resources by identifier than by name.
1357 *
1358 * @param name The name of the desired resource. This is passed to
1359 * getIdentifier() with a default type of "string".
1360 * @param outValue Object in which to place the resource data.
1361 * @param resolveRefs If true, a resource that is a reference to another
1362 * resource will be followed so that you receive the
1363 * actual final resource data. If false, the TypedValue
1364 * will be filled in with the reference itself.
1365 *
1366 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1367 *
1368 */
1369 public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1370 throws NotFoundException {
1371 int id = getIdentifier(name, "string", null);
1372 if (id != 0) {
1373 getValue(id, outValue, resolveRefs);
1374 return;
1375 }
1376 throw new NotFoundException("String resource name " + name);
1377 }
1378
1379 /**
1380 * This class holds the current attribute values for a particular theme.
1381 * In other words, a Theme is a set of values for resource attributes;
1382 * these are used in conjunction with {@link TypedArray}
1383 * to resolve the final value for an attribute.
1384 *
1385 * <p>The Theme's attributes come into play in two ways: (1) a styled
1386 * attribute can explicit reference a value in the theme through the
1387 * "?themeAttribute" syntax; (2) if no value has been defined for a
1388 * particular styled attribute, as a last resort we will try to find that
1389 * attribute's value in the Theme.
1390 *
1391 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1392 * retrieve XML attributes with style and theme information applied.
1393 */
1394 public final class Theme {
1395 /**
1396 * Place new attribute values into the theme. The style resource
1397 * specified by <var>resid</var> will be retrieved from this Theme's
1398 * resources, its values placed into the Theme object.
1399 *
1400 * <p>The semantics of this function depends on the <var>force</var>
1401 * argument: If false, only values that are not already defined in
1402 * the theme will be copied from the system resource; otherwise, if
1403 * any of the style's attributes are already defined in the theme, the
1404 * current values in the theme will be overwritten.
1405 *
Alan Viverette75257ce2014-05-22 19:31:38 -07001406 * @param resId The resource ID of a style resource from which to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 * obtain attribute values.
1408 * @param force If true, values in the style resource will always be
1409 * used in the theme; otherwise, they will only be used
1410 * if not already defined in the theme.
1411 */
Alan Viverette75257ce2014-05-22 19:31:38 -07001412 public void applyStyle(int resId, boolean force) {
Alan Viverette395cd012015-08-11 17:27:04 -04001413 synchronized (mKey) {
1414 AssetManager.applyThemeStyle(mTheme, resId, force);
Alan Viverette52b999f2014-03-24 18:00:26 -07001415
Alan Viverette395cd012015-08-11 17:27:04 -04001416 mThemeResId = resId;
1417 mKey.append(resId, force);
1418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420
1421 /**
1422 * Set this theme to hold the same contents as the theme
1423 * <var>other</var>. If both of these themes are from the same
1424 * Resources object, they will be identical after this function
1425 * returns. If they are from different Resources, only the resources
1426 * they have in common will be set in this theme.
1427 *
1428 * @param other The existing Theme to copy from.
1429 */
1430 public void setTo(Theme other) {
Alan Viverette395cd012015-08-11 17:27:04 -04001431 synchronized (mKey) {
1432 synchronized (other.mKey) {
1433 AssetManager.copyTheme(mTheme, other.mTheme);
Alan Viverette52b999f2014-03-24 18:00:26 -07001434
Alan Viverette395cd012015-08-11 17:27:04 -04001435 mThemeResId = other.mThemeResId;
1436 mKey.setTo(other.getKey());
1437 }
1438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440
1441 /**
John Spurlock330dd532012-12-18 12:03:11 -05001442 * Return a TypedArray holding the values defined by
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 * <var>Theme</var> which are listed in <var>attrs</var>.
1444 *
Scott Main183bf112012-08-13 19:12:13 -07001445 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1446 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 *
1448 * @param attrs The desired attributes.
1449 *
1450 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1451 *
1452 * @return Returns a TypedArray holding an array of the attribute values.
1453 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1454 * when done with it.
1455 *
1456 * @see Resources#obtainAttributes
1457 * @see #obtainStyledAttributes(int, int[])
1458 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1459 */
Tor Norbyec91531a2015-04-01 17:41:55 -07001460 public TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001461 synchronized (mKey) {
1462 final int len = attrs.length;
1463 final TypedArray array = TypedArray.obtain(Resources.this, len);
1464 array.mTheme = this;
1465 AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
1466 return array;
1467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
1469
1470 /**
John Spurlock330dd532012-12-18 12:03:11 -05001471 * Return a TypedArray holding the values defined by the style
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 * resource <var>resid</var> which are listed in <var>attrs</var>.
1473 *
Scott Main183bf112012-08-13 19:12:13 -07001474 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1475 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 *
Alan Viverette395cd012015-08-11 17:27:04 -04001477 * @param resId The desired style resource.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 * @param attrs The desired attributes in the style.
1479 *
1480 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1481 *
1482 * @return Returns a TypedArray holding an array of the attribute values.
1483 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1484 * when done with it.
1485 *
1486 * @see Resources#obtainAttributes
1487 * @see #obtainStyledAttributes(int[])
1488 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1489 */
Alan Viverette395cd012015-08-11 17:27:04 -04001490 public TypedArray obtainStyledAttributes(@StyleRes int resId, @StyleableRes int[] attrs)
Tor Norbyec91531a2015-04-01 17:41:55 -07001491 throws NotFoundException {
Alan Viverette395cd012015-08-11 17:27:04 -04001492 synchronized (mKey) {
1493 final int len = attrs.length;
1494 final TypedArray array = TypedArray.obtain(Resources.this, len);
1495 array.mTheme = this;
1496 AssetManager.applyStyle(mTheme, 0, resId, 0, attrs, array.mData, array.mIndices);
1497 return array;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500
1501 /**
John Spurlock330dd532012-12-18 12:03:11 -05001502 * Return a TypedArray holding the attribute values in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 * <var>set</var>
1504 * that are listed in <var>attrs</var>. In addition, if the given
1505 * AttributeSet specifies a style class (through the "style" attribute),
1506 * that style will be applied on top of the base attributes it defines.
1507 *
Scott Main183bf112012-08-13 19:12:13 -07001508 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1509 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 *
1511 * <p>When determining the final value of a particular attribute, there
1512 * are four inputs that come into play:</p>
1513 *
1514 * <ol>
1515 * <li> Any attribute values in the given AttributeSet.
1516 * <li> The style resource specified in the AttributeSet (named
1517 * "style").
1518 * <li> The default style specified by <var>defStyleAttr</var> and
1519 * <var>defStyleRes</var>
1520 * <li> The base values in this theme.
1521 * </ol>
1522 *
1523 * <p>Each of these inputs is considered in-order, with the first listed
1524 * taking precedence over the following ones. In other words, if in the
1525 * AttributeSet you have supplied <code>&lt;Button
1526 * textColor="#ff000000"&gt;</code>, then the button's text will
1527 * <em>always</em> be black, regardless of what is specified in any of
1528 * the styles.
1529 *
1530 * @param set The base set of attribute values. May be null.
1531 * @param attrs The desired attributes to be retrieved.
1532 * @param defStyleAttr An attribute in the current theme that contains a
1533 * reference to a style resource that supplies
John Spurlock330dd532012-12-18 12:03:11 -05001534 * defaults values for the TypedArray. Can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 * 0 to not look for defaults.
1536 * @param defStyleRes A resource identifier of a style resource that
John Spurlock330dd532012-12-18 12:03:11 -05001537 * supplies default values for the TypedArray,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 * used only if defStyleAttr is 0 or can not be found
1539 * in the theme. Can be 0 to not look for defaults.
1540 *
1541 * @return Returns a TypedArray holding an array of the attribute values.
1542 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1543 * when done with it.
1544 *
1545 * @see Resources#obtainAttributes
1546 * @see #obtainStyledAttributes(int[])
1547 * @see #obtainStyledAttributes(int, int[])
1548 */
1549 public TypedArray obtainStyledAttributes(AttributeSet set,
Tor Norbyec91531a2015-04-01 17:41:55 -07001550 @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
Alan Viverette395cd012015-08-11 17:27:04 -04001551 synchronized (mKey) {
1552 final int len = attrs.length;
1553 final TypedArray array = TypedArray.obtain(Resources.this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554
Alan Viverette395cd012015-08-11 17:27:04 -04001555 // XXX note that for now we only work with compiled XML files.
1556 // To support generic XML files we will need to manually parse
1557 // out the attributes from the XML file (applying type information
1558 // contained in the resources and such).
1559 final XmlBlock.Parser parser = (XmlBlock.Parser) set;
1560 AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1561 parser != null ? parser.mParseState : 0,
1562 attrs, array.mData, array.mIndices);
1563 array.mTheme = this;
1564 array.mXml = parser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
Alan Viverette395cd012015-08-11 17:27:04 -04001566 return array;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569
1570 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001571 * Retrieve the values for a set of attributes in the Theme. The
1572 * contents of the typed array are ultimately filled in by
1573 * {@link Resources#getValue}.
1574 *
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001575 * @param values The base set of attribute values, must be equal in
1576 * length to {@code attrs}. All values must be of type
1577 * {@link TypedValue#TYPE_ATTRIBUTE}.
Alan Viverette52b999f2014-03-24 18:00:26 -07001578 * @param attrs The desired attributes to be retrieved.
Alan Viverette52b999f2014-03-24 18:00:26 -07001579 * @return Returns a TypedArray holding an array of the attribute
1580 * values. Be sure to call {@link TypedArray#recycle()}
1581 * when done with it.
1582 * @hide
1583 */
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001584 @NonNull
1585 public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001586 synchronized (mKey) {
1587 final int len = attrs.length;
1588 if (values == null || len != values.length) {
1589 throw new IllegalArgumentException(
1590 "Base attribute values must the same length as attrs");
1591 }
1592
1593 final TypedArray array = TypedArray.obtain(Resources.this, len);
1594 AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
1595 array.mTheme = this;
1596 array.mXml = null;
1597
1598 return array;
Alan Viverette52b999f2014-03-24 18:00:26 -07001599 }
Alan Viverette52b999f2014-03-24 18:00:26 -07001600 }
1601
1602 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 * Retrieve the value of an attribute in the Theme. The contents of
1604 * <var>outValue</var> are ultimately filled in by
1605 * {@link Resources#getValue}.
1606 *
1607 * @param resid The resource identifier of the desired theme
1608 * attribute.
1609 * @param outValue Filled in with the ultimate resource value supplied
1610 * by the attribute.
1611 * @param resolveRefs If true, resource references will be walked; if
1612 * false, <var>outValue</var> may be a
1613 * TYPE_REFERENCE. In either case, it will never
1614 * be a TYPE_ATTRIBUTE.
1615 *
1616 * @return boolean Returns true if the attribute was found and
1617 * <var>outValue</var> is valid, else false.
1618 */
Alan Viverette52b999f2014-03-24 18:00:26 -07001619 public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001620 synchronized (mKey) {
1621 return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624
1625 /**
Jon Miranda042ad632014-09-03 17:57:35 -07001626 * Gets all of the attribute ids associated with this {@link Theme}. For debugging only.
1627 *
1628 * @return The int array containing attribute ids associated with this {@link Theme}.
1629 * @hide
1630 */
1631 public int[] getAllAttributes() {
1632 return mAssets.getStyleAttributes(getAppliedStyleResId());
1633 }
1634
1635 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001636 * Returns the resources to which this theme belongs.
1637 *
1638 * @return Resources to which this theme belongs.
1639 */
1640 public Resources getResources() {
1641 return Resources.this;
1642 }
1643
1644 /**
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001645 * Return a drawable object associated with a particular resource ID
1646 * and styled for the Theme.
1647 *
1648 * @param id The desired resource identifier, as generated by the aapt
1649 * tool. This integer encodes the package, type, and resource
1650 * entry. The value 0 is an invalid identifier.
1651 * @return Drawable An object that can be used to draw this resource.
1652 * @throws NotFoundException Throws NotFoundException if the given ID
1653 * does not exist.
1654 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001655 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001656 return Resources.this.getDrawable(id, this);
1657 }
1658
1659 /**
Alan Viverettec1d52792015-05-05 09:49:03 -07001660 * Returns a bit mask of configuration changes that will impact this
1661 * theme (and thus require completely reloading it).
1662 *
1663 * @return a bit mask of configuration changes, as defined by
1664 * {@link ActivityInfo}
1665 * @see ActivityInfo
1666 */
1667 public int getChangingConfigurations() {
Alan Viverette395cd012015-08-11 17:27:04 -04001668 synchronized (mKey) {
1669 final int nativeChangingConfig =
1670 AssetManager.getThemeChangingConfigurations(mTheme);
1671 return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
1672 }
Alan Viverettec1d52792015-05-05 09:49:03 -07001673 }
1674
1675 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 * Print contents of this theme out to the log. For debugging only.
1677 *
1678 * @param priority The log priority to use.
1679 * @param tag The log tag to use.
1680 * @param prefix Text to prefix each line printed.
1681 */
1682 public void dump(int priority, String tag, String prefix) {
Alan Viverette395cd012015-08-11 17:27:04 -04001683 synchronized (mKey) {
1684 AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001687
1688 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 protected void finalize() throws Throwable {
1690 super.finalize();
1691 mAssets.releaseTheme(mTheme);
1692 }
1693
1694 /*package*/ Theme() {
1695 mAssets = Resources.this.mAssets;
1696 mTheme = mAssets.createTheme();
1697 }
1698
Alan Viverettee54d2452015-05-06 10:41:43 -07001699 /** Unique key for the series of styles applied to this theme. */
1700 private final ThemeKey mKey = new ThemeKey();
1701
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001702 @SuppressWarnings("hiding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 private final AssetManager mAssets;
Ashok Bhat896043d2014-01-17 16:02:38 +00001704 private final long mTheme;
Alan Viverette52b999f2014-03-24 18:00:26 -07001705
Alan Viverette351f0c12014-03-28 15:25:27 -07001706 /** Resource identifier for the theme. */
Alan Viverette52b999f2014-03-24 18:00:26 -07001707 private int mThemeResId = 0;
Deepanshu Guptabfec73c2014-03-11 18:02:44 -07001708
1709 // Needed by layoutlib.
1710 /*package*/ long getNativeTheme() {
1711 return mTheme;
1712 }
1713
1714 /*package*/ int getAppliedStyleResId() {
1715 return mThemeResId;
1716 }
Alan Viverette75257ce2014-05-22 19:31:38 -07001717
Alan Viverettee54d2452015-05-06 10:41:43 -07001718 /*package*/ ThemeKey getKey() {
Alan Viverette75257ce2014-05-22 19:31:38 -07001719 return mKey;
1720 }
Jon Miranda836c0a82014-08-11 12:32:26 -07001721
1722 private String getResourceNameFromHexString(String hexString) {
1723 return getResourceName(Integer.parseInt(hexString, 16));
1724 }
1725
1726 /**
Alan Viverettee54d2452015-05-06 10:41:43 -07001727 * Parses {@link #mKey} and returns a String array that holds pairs of
1728 * adjacent Theme data: resource name followed by whether or not it was
1729 * forced, as specified by {@link #applyStyle(int, boolean)}.
Jon Miranda836c0a82014-08-11 12:32:26 -07001730 *
1731 * @hide
1732 */
1733 @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
1734 public String[] getTheme() {
Alan Viverette395cd012015-08-11 17:27:04 -04001735 synchronized (mKey) {
1736 final int N = mKey.mCount;
1737 final String[] themes = new String[N * 2];
1738 for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
1739 final int resId = mKey.mResId[j];
1740 final boolean forced = mKey.mForce[j];
1741 try {
1742 themes[i] = getResourceName(resId);
1743 } catch (NotFoundException e) {
1744 themes[i] = Integer.toHexString(i);
1745 }
1746 themes[i + 1] = forced ? "forced" : "not forced";
Siva Velusamy0d857b92015-04-22 10:23:56 -07001747 }
Alan Viverette395cd012015-08-11 17:27:04 -04001748 return themes;
Jon Miranda836c0a82014-08-11 12:32:26 -07001749 }
Jon Miranda836c0a82014-08-11 12:32:26 -07001750 }
Alan Viverettee54d2452015-05-06 10:41:43 -07001751
Siva Velusamy0d857b92015-04-22 10:23:56 -07001752 /** @hide */
1753 public void encode(@NonNull ViewHierarchyEncoder encoder) {
1754 encoder.beginObject(this);
Alan Viveretteac674092015-05-08 11:04:47 -07001755 final String[] properties = getTheme();
Siva Velusamy0d857b92015-04-22 10:23:56 -07001756 for (int i = 0; i < properties.length; i += 2) {
1757 encoder.addProperty(properties[i], properties[i+1]);
1758 }
1759 encoder.endObject();
1760 }
1761
Alan Viverettee54d2452015-05-06 10:41:43 -07001762 /**
1763 * Rebases the theme against the parent Resource object's current
1764 * configuration by re-applying the styles passed to
1765 * {@link #applyStyle(int, boolean)}.
1766 *
1767 * @hide
1768 */
1769 public void rebase() {
Alan Viverette395cd012015-08-11 17:27:04 -04001770 synchronized (mKey) {
1771 AssetManager.clearTheme(mTheme);
Alan Viverettee54d2452015-05-06 10:41:43 -07001772
Alan Viverette395cd012015-08-11 17:27:04 -04001773 // Reapply the same styles in the same order.
1774 for (int i = 0; i < mKey.mCount; i++) {
1775 final int resId = mKey.mResId[i];
1776 final boolean force = mKey.mForce[i];
1777 AssetManager.applyThemeStyle(mTheme, resId, force);
1778 }
Alan Viverettee54d2452015-05-06 10:41:43 -07001779 }
1780 }
1781 }
1782
1783 static class ThemeKey implements Cloneable {
1784 int[] mResId;
1785 boolean[] mForce;
1786 int mCount;
1787
1788 private int mHashCode = 0;
1789
1790 public void append(int resId, boolean force) {
1791 if (mResId == null) {
1792 mResId = new int[4];
1793 }
1794
1795 if (mForce == null) {
1796 mForce = new boolean[4];
1797 }
1798
1799 mResId = GrowingArrayUtils.append(mResId, mCount, resId);
1800 mForce = GrowingArrayUtils.append(mForce, mCount, force);
1801 mCount++;
1802
1803 mHashCode = 31 * (31 * mHashCode + resId) + (force ? 1 : 0);
1804 }
1805
1806 /**
1807 * Sets up this key as a deep copy of another key.
1808 *
1809 * @param other the key to deep copy into this key
1810 */
1811 public void setTo(ThemeKey other) {
1812 mResId = other.mResId == null ? null : other.mResId.clone();
1813 mForce = other.mForce == null ? null : other.mForce.clone();
1814 mCount = other.mCount;
1815 }
1816
1817 @Override
1818 public int hashCode() {
1819 return mHashCode;
1820 }
1821
1822 @Override
1823 public boolean equals(Object o) {
1824 if (this == o) {
1825 return true;
1826 }
1827
1828 if (o == null || getClass() != o.getClass() || hashCode() != o.hashCode()) {
1829 return false;
1830 }
1831
1832 final ThemeKey t = (ThemeKey) o;
1833 if (mCount != t.mCount) {
1834 return false;
1835 }
1836
1837 final int N = mCount;
1838 for (int i = 0; i < N; i++) {
1839 if (mResId[i] != t.mResId[i] || mForce[i] != t.mForce[i]) {
1840 return false;
1841 }
1842 }
1843
1844 return true;
1845 }
1846
1847 /**
1848 * @return a shallow copy of this key
1849 */
1850 @Override
1851 public ThemeKey clone() {
1852 final ThemeKey other = new ThemeKey();
1853 other.mResId = mResId;
1854 other.mForce = mForce;
1855 other.mCount = mCount;
John Reck4feb3262015-07-13 14:42:43 -07001856 other.mHashCode = mHashCode;
Alan Viverettee54d2452015-05-06 10:41:43 -07001857 return other;
1858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860
1861 /**
1862 * Generate a new Theme object for this set of Resources. It initially
1863 * starts out empty.
Jon Miranda836c0a82014-08-11 12:32:26 -07001864 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 * @return Theme The newly created Theme container.
1866 */
1867 public final Theme newTheme() {
1868 return new Theme();
1869 }
1870
1871 /**
1872 * Retrieve a set of basic attribute values from an AttributeSet, not
1873 * performing styling of them using a theme and/or style resources.
Jon Miranda836c0a82014-08-11 12:32:26 -07001874 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 * @param set The current attribute values to retrieve.
1876 * @param attrs The specific attributes to be retrieved.
1877 * @return Returns a TypedArray holding an array of the attribute values.
1878 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1879 * when done with it.
1880 *
1881 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1882 */
1883 public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1884 int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001885 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886
1887 // XXX note that for now we only work with compiled XML files.
1888 // To support generic XML files we will need to manually parse
1889 // out the attributes from the XML file (applying type information
1890 // contained in the resources and such).
1891 XmlBlock.Parser parser = (XmlBlock.Parser)set;
1892 mAssets.retrieveAttributes(parser.mParseState, attrs,
1893 array.mData, array.mIndices);
1894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 array.mXml = parser;
1896
1897 return array;
1898 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 /**
1901 * Store the newly updated configuration.
1902 */
1903 public void updateConfiguration(Configuration config,
1904 DisplayMetrics metrics) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001905 updateConfiguration(config, metrics, null);
1906 }
1907
1908 /**
1909 * @hide
1910 */
1911 public void updateConfiguration(Configuration config,
1912 DisplayMetrics metrics, CompatibilityInfo compat) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001913 synchronized (mAccessLock) {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001914 if (false) {
1915 Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1916 + mConfiguration + " old compat is " + mCompatibilityInfo);
1917 Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1918 + config + " new compat is " + compat);
1919 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001920 if (compat != null) {
1921 mCompatibilityInfo = compat;
1922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 if (metrics != null) {
1924 mMetrics.setTo(metrics);
1925 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001926 // NOTE: We should re-arrange this code to create a Display
1927 // with the CompatibilityInfo that is used everywhere we deal
1928 // with the display in relation to this app, rather than
1929 // doing the conversion here. This impl should be okay because
1930 // we make sure to return a compatible display in the places
1931 // where there are public APIs to retrieve the display... but
1932 // it would be cleaner and more maintainble to just be
1933 // consistently dealing with a compatible display everywhere in
1934 // the framework.
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07001935 mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1936
Alan Viverettea8636c92015-03-27 10:44:39 -07001937 final int configChanges = calcConfigChanges(config);
Roozbeh Pournaderdad10062015-12-14 16:15:52 -08001938
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001939 LocaleList locales = mConfiguration.getLocales();
Raph Levien1f0945e2016-01-20 12:16:50 -08001940 if (locales.isEmpty()) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -08001941 locales = LocaleList.getAdjustedDefault();
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001942 mConfiguration.setLocales(locales);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001943 }
Dianne Hackborn756220b2012-08-14 16:45:30 -07001944 if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1945 mMetrics.densityDpi = mConfiguration.densityDpi;
1946 mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1947 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001948 mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001949
Alan Viverettea8636c92015-03-27 10:44:39 -07001950 final int width, height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1952 width = mMetrics.widthPixels;
1953 height = mMetrics.heightPixels;
1954 } else {
1955 //noinspection SuspiciousNameCombination
1956 width = mMetrics.heightPixels;
1957 //noinspection SuspiciousNameCombination
1958 height = mMetrics.widthPixels;
1959 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001960
1961 final int keyboardHidden;
1962 if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1963 && mConfiguration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
Alan Viverettea8636c92015-03-27 10:44:39 -07001965 } else {
1966 keyboardHidden = mConfiguration.keyboardHidden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
Roozbeh Pournaderfee44842016-02-04 15:24:24 -08001970 adjustLanguageTag(locales.get(0).toLanguageTag()),
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001971 mConfiguration.orientation,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 mConfiguration.touchscreen,
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001973 mConfiguration.densityDpi, mConfiguration.keyboard,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 keyboardHidden, mConfiguration.navigation, width, height,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07001975 mConfiguration.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07001976 mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08001977 mConfiguration.screenLayout, mConfiguration.uiMode,
1978 Build.VERSION.RESOURCES_SDK_INT);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001979
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001980 if (DEBUG_CONFIG) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001981 Slog.i(TAG, "**** Updating config of " + this + ": final config is "
1982 + mConfiguration + " final compat is " + mCompatibilityInfo);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001983 }
1984
Alan Viverettee54d2452015-05-06 10:41:43 -07001985 mDrawableCache.onConfigurationChange(configChanges);
1986 mColorDrawableCache.onConfigurationChange(configChanges);
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08001987 mComplexColorCache.onConfigurationChange(configChanges);
Yigit Boyard422dc32014-09-25 12:23:35 -07001988 mAnimatorCache.onConfigurationChange(configChanges);
1989 mStateListAnimatorCache.onConfigurationChange(configChanges);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 flushLayoutCache();
1992 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001993 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (mPluralRule != null) {
Roozbeh Pournaderfee44842016-02-04 15:24:24 -08001995 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997 }
1998 }
1999
Yigit Boyard422dc32014-09-25 12:23:35 -07002000 /**
2001 * Called by ConfigurationBoundResourceCacheTest via reflection.
2002 */
2003 private int calcConfigChanges(Configuration config) {
2004 int configChanges = 0xfffffff;
2005 if (config != null) {
2006 mTmpConfig.setTo(config);
2007 int density = config.densityDpi;
2008 if (density == Configuration.DENSITY_DPI_UNDEFINED) {
2009 density = mMetrics.noncompatDensityDpi;
2010 }
2011
2012 mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
2013
Roozbeh Pournader47571c72015-09-01 14:07:04 -07002014 if (mTmpConfig.getLocales().isEmpty()) {
2015 mTmpConfig.setLocales(LocaleList.getDefault());
Yigit Boyard422dc32014-09-25 12:23:35 -07002016 }
2017 configChanges = mConfiguration.updateFrom(mTmpConfig);
2018 configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
2019 }
2020 return configChanges;
2021 }
2022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 /**
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002024 * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
2025 * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
2026 *
2027 * All released versions of android prior to "L" used the deprecated language
2028 * tags, so we will need to support them for backwards compatibility.
2029 *
2030 * Note that this conversion needs to take place *after* the call to
2031 * {@code toLanguageTag} because that will convert all the deprecated codes to
2032 * the new ones, even if they're set manually.
2033 */
2034 private static String adjustLanguageTag(String languageTag) {
2035 final int separator = languageTag.indexOf('-');
2036 final String language;
2037 final String remainder;
2038
2039 if (separator == -1) {
2040 language = languageTag;
2041 remainder = "";
2042 } else {
2043 language = languageTag.substring(0, separator);
2044 remainder = languageTag.substring(separator);
2045 }
2046
Narayan Kamath4c6ce232014-07-18 16:09:36 +01002047 return Locale.adjustLanguageCode(language) + remainder;
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002048 }
2049
2050 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 * Update the system resources configuration if they have previously
2052 * been initialized.
2053 *
2054 * @hide
2055 */
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002056 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
2057 CompatibilityInfo compat) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 if (mSystem != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002059 mSystem.updateConfiguration(config, metrics, compat);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 //Log.i(TAG, "Updated system resources " + mSystem
2061 // + ": " + mSystem.getConfiguration());
2062 }
2063 }
2064
2065 /**
2066 * Return the current display metrics that are in effect for this resource
2067 * object. The returned object should be treated as read-only.
2068 *
2069 * @return The resource's current display metrics.
2070 */
2071 public DisplayMetrics getDisplayMetrics() {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002072 if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
2073 + "x" + mMetrics.heightPixels + " " + mMetrics.density);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 return mMetrics;
2075 }
2076
2077 /**
2078 * Return the current configuration that is in effect for this resource
2079 * object. The returned object should be treated as read-only.
2080 *
2081 * @return The resource's current configuration.
2082 */
2083 public Configuration getConfiguration() {
2084 return mConfiguration;
2085 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07002086
2087 /** @hide */
2088 public Configuration[] getSizeConfigurations() {
2089 return mAssets.getSizeConfigurations();
2090 };
2091
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002092 /**
2093 * Return the compatibility mode information for the application.
2094 * The returned object should be treated as read-only.
2095 *
Dianne Hackborn3904d032011-05-27 12:09:11 -07002096 * @return compatibility info.
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002097 * @hide
2098 */
2099 public CompatibilityInfo getCompatibilityInfo() {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002100 return mCompatibilityInfo;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102
2103 /**
Dianne Hackborna53b8282009-07-17 11:13:48 -07002104 * This is just for testing.
2105 * @hide
2106 */
2107 public void setCompatibilityInfo(CompatibilityInfo ci) {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002108 if (ci != null) {
2109 mCompatibilityInfo = ci;
2110 updateConfiguration(mConfiguration, mMetrics);
2111 }
Dianne Hackborna53b8282009-07-17 11:13:48 -07002112 }
2113
2114 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 * Return a resource identifier for the given resource name. A fully
2116 * qualified resource name is of the form "package:type/entry". The first
2117 * two components (package and type) are optional if defType and
2118 * defPackage, respectively, are specified here.
2119 *
2120 * <p>Note: use of this function is discouraged. It is much more
2121 * efficient to retrieve resources by identifier than by name.
2122 *
2123 * @param name The name of the desired resource.
2124 * @param defType Optional default resource type to find, if "type/" is
2125 * not included in the name. Can be null to require an
2126 * explicit type.
2127 * @param defPackage Optional default package to find, if "package:" is
2128 * not included in the name. Can be null to require an
2129 * explicit package.
2130 *
2131 * @return int The associated resource identifier. Returns 0 if no such
2132 * resource was found. (0 is not a valid resource ID.)
2133 */
2134 public int getIdentifier(String name, String defType, String defPackage) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002135 if (name == null) {
2136 throw new NullPointerException("name is null");
2137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 try {
2139 return Integer.parseInt(name);
2140 } catch (Exception e) {
2141 // Ignore
2142 }
2143 return mAssets.getResourceIdentifier(name, defType, defPackage);
2144 }
2145
2146 /**
Jeff Sharkey47b50332013-03-15 14:46:46 -07002147 * Return true if given resource identifier includes a package.
2148 *
2149 * @hide
2150 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002151 public static boolean resourceHasPackage(@AnyRes int resid) {
Jeff Sharkey47b50332013-03-15 14:46:46 -07002152 return (resid >>> 24) != 0;
2153 }
2154
2155 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 * Return the full name for a given resource identifier. This name is
2157 * a single string of the form "package:type/entry".
2158 *
2159 * @param resid The resource identifier whose name is to be retrieved.
2160 *
2161 * @return A string holding the name of the resource.
2162 *
2163 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2164 *
2165 * @see #getResourcePackageName
2166 * @see #getResourceTypeName
2167 * @see #getResourceEntryName
2168 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002169 public String getResourceName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 String str = mAssets.getResourceName(resid);
2171 if (str != null) return str;
2172 throw new NotFoundException("Unable to find resource ID #0x"
2173 + Integer.toHexString(resid));
2174 }
2175
2176 /**
2177 * Return the package name for a given resource identifier.
2178 *
2179 * @param resid The resource identifier whose package name is to be
2180 * retrieved.
2181 *
2182 * @return A string holding the package name of the resource.
2183 *
2184 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2185 *
2186 * @see #getResourceName
2187 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002188 public String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 String str = mAssets.getResourcePackageName(resid);
2190 if (str != null) return str;
2191 throw new NotFoundException("Unable to find resource ID #0x"
2192 + Integer.toHexString(resid));
2193 }
2194
2195 /**
2196 * Return the type name for a given resource identifier.
2197 *
2198 * @param resid The resource identifier whose type name is to be
2199 * retrieved.
2200 *
2201 * @return A string holding the type name of the resource.
2202 *
2203 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2204 *
2205 * @see #getResourceName
2206 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002207 public String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 String str = mAssets.getResourceTypeName(resid);
2209 if (str != null) return str;
2210 throw new NotFoundException("Unable to find resource ID #0x"
2211 + Integer.toHexString(resid));
2212 }
2213
2214 /**
2215 * Return the entry name for a given resource identifier.
2216 *
2217 * @param resid The resource identifier whose entry name is to be
2218 * retrieved.
2219 *
2220 * @return A string holding the entry name of the resource.
2221 *
2222 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2223 *
2224 * @see #getResourceName
2225 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002226 public String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 String str = mAssets.getResourceEntryName(resid);
2228 if (str != null) return str;
2229 throw new NotFoundException("Unable to find resource ID #0x"
2230 + Integer.toHexString(resid));
2231 }
2232
2233 /**
2234 * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2235 * an XML file. You call this when you are at the parent tag of the
Dianne Hackborndef15372010-08-15 12:43:52 -07002236 * 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 -08002237 * This will call {@link #parseBundleExtra} for each extra tag encountered.
2238 *
2239 * @param parser The parser from which to retrieve the extras.
2240 * @param outBundle A Bundle in which to place all parsed extras.
2241 * @throws XmlPullParserException
2242 * @throws IOException
2243 */
2244 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2245 throws XmlPullParserException, IOException {
2246 int outerDepth = parser.getDepth();
2247 int type;
2248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2249 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2250 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2251 continue;
2252 }
2253
2254 String nodeName = parser.getName();
2255 if (nodeName.equals("extra")) {
2256 parseBundleExtra("extra", parser, outBundle);
2257 XmlUtils.skipCurrentTag(parser);
2258
2259 } else {
2260 XmlUtils.skipCurrentTag(parser);
2261 }
2262 }
2263 }
2264
2265 /**
2266 * Parse a name/value pair out of an XML tag holding that data. The
2267 * AttributeSet must be holding the data defined by
2268 * {@link android.R.styleable#Extra}. The following value types are supported:
2269 * <ul>
2270 * <li> {@link TypedValue#TYPE_STRING}:
2271 * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2272 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2273 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2274 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2275 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2276 * <li> {@link TypedValue#TYPE_FLOAT}:
2277 * {@link Bundle#putCharSequence Bundle.putFloat()}
2278 * </ul>
2279 *
2280 * @param tagName The name of the tag these attributes come from; this is
2281 * only used for reporting error messages.
2282 * @param attrs The attributes from which to retrieve the name/value pair.
2283 * @param outBundle The Bundle in which to place the parsed value.
2284 * @throws XmlPullParserException If the attributes are not valid.
2285 */
2286 public void parseBundleExtra(String tagName, AttributeSet attrs,
2287 Bundle outBundle) throws XmlPullParserException {
2288 TypedArray sa = obtainAttributes(attrs,
2289 com.android.internal.R.styleable.Extra);
2290
2291 String name = sa.getString(
2292 com.android.internal.R.styleable.Extra_name);
2293 if (name == null) {
2294 sa.recycle();
2295 throw new XmlPullParserException("<" + tagName
2296 + "> requires an android:name attribute at "
2297 + attrs.getPositionDescription());
2298 }
2299
2300 TypedValue v = sa.peekValue(
2301 com.android.internal.R.styleable.Extra_value);
2302 if (v != null) {
2303 if (v.type == TypedValue.TYPE_STRING) {
2304 CharSequence cs = v.coerceToString();
2305 outBundle.putCharSequence(name, cs);
2306 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2307 outBundle.putBoolean(name, v.data != 0);
2308 } else if (v.type >= TypedValue.TYPE_FIRST_INT
2309 && v.type <= TypedValue.TYPE_LAST_INT) {
2310 outBundle.putInt(name, v.data);
2311 } else if (v.type == TypedValue.TYPE_FLOAT) {
2312 outBundle.putFloat(name, v.getFloat());
2313 } else {
2314 sa.recycle();
2315 throw new XmlPullParserException("<" + tagName
2316 + "> only supports string, integer, float, color, and boolean at "
2317 + attrs.getPositionDescription());
2318 }
2319 } else {
2320 sa.recycle();
2321 throw new XmlPullParserException("<" + tagName
2322 + "> requires an android:value or android:resource attribute at "
2323 + attrs.getPositionDescription());
2324 }
2325
2326 sa.recycle();
2327 }
2328
2329 /**
2330 * Retrieve underlying AssetManager storage for these resources.
2331 */
2332 public final AssetManager getAssets() {
2333 return mAssets;
2334 }
2335
2336 /**
2337 * Call this to remove all cached loaded layout resources from the
2338 * Resources object. Only intended for use with performance testing
2339 * tools.
2340 */
2341 public final void flushLayoutCache() {
Alan Viverette10979612016-01-06 15:27:35 -05002342 final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
2343 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
2344 synchronized (cachedXmlBlockFiles) {
2345 final int num = cachedXmlBlockFiles.length;
2346 for (int i = 0; i < num; i++) {
2347 final XmlBlock oldBlock = cachedXmlBlocks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 if (oldBlock != null) {
2349 oldBlock.close();
2350 }
Alan Viverette10979612016-01-06 15:27:35 -05002351 cachedXmlBlockFiles[i] = null;
2352 cachedXmlBlocks[i] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
2354 }
2355 }
2356
2357 /**
2358 * Start preloading of resource data using this Resources object. Only
2359 * for use by the zygote process for loading common system resources.
2360 * {@hide}
2361 */
2362 public final void startPreloading() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002363 synchronized (sSync) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002364 if (sPreloaded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 throw new IllegalStateException("Resources already preloaded");
2366 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002367 sPreloaded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 mPreloading = true;
Alan Viverette4d07bc92015-11-16 10:19:12 -05002369 mConfiguration.densityDpi = DisplayMetrics.DENSITY_DEVICE;
Dianne Hackborndde331c2012-08-03 14:01:57 -07002370 updateConfiguration(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 }
2372 }
2373
2374 /**
2375 * Called by zygote when it is done preloading resources, to change back
2376 * to normal Resources operation.
2377 */
2378 public final void finishPreloading() {
2379 if (mPreloading) {
2380 mPreloading = false;
2381 flushLayoutCache();
2382 }
2383 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002384
Romain Guy3b748a42013-04-17 18:54:38 -07002385 /**
2386 * @hide
2387 */
Alan Viverette52b999f2014-03-24 18:00:26 -07002388 public LongSparseArray<ConstantState> getPreloadedDrawables() {
Romain Guy3b748a42013-04-17 18:54:38 -07002389 return sPreloadedDrawables[0];
2390 }
2391
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002392 private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2393 int resourceId, String name) {
2394 // We allow preloading of resources even if they vary by font scale (which
2395 // doesn't impact resource selection) or density (which we handle specially by
2396 // simply turning off all preloading), as well as any other configs specified
2397 // by the caller.
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002398 if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002399 ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002400 String resName;
2401 try {
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002402 resName = getResourceName(resourceId);
Dianne Hackborndde331c2012-08-03 14:01:57 -07002403 } catch (NotFoundException e) {
2404 resName = "?";
2405 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002406 // This should never happen in production, so we should log a
2407 // warning even if we're not debugging.
Dianne Hackborndde331c2012-08-03 14:01:57 -07002408 Log.w(TAG, "Preloaded " + name + " resource #0x"
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002409 + Integer.toHexString(resourceId)
Dianne Hackborndde331c2012-08-03 14:01:57 -07002410 + " (" + resName + ") that varies with configuration!!");
2411 return false;
2412 }
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -07002413 if (TRACE_FOR_PRELOAD) {
2414 String resName;
2415 try {
2416 resName = getResourceName(resourceId);
2417 } catch (NotFoundException e) {
2418 resName = "?";
2419 }
2420 Log.w(TAG, "Preloading " + name + " resource #0x"
2421 + Integer.toHexString(resourceId)
2422 + " (" + resName + ")");
2423 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002424 return true;
2425 }
2426
Alan Viverette0f1c95e2015-06-05 10:17:21 -07002427 @Nullable
2428 Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
Alan Viverette7941a7f2016-01-06 11:11:53 -05002429 return loadDrawable(value, id, theme, true);
2430 }
2431
2432 @Nullable
2433 Drawable loadDrawable(TypedValue value, int id, Theme theme, boolean useCache)
2434 throws NotFoundException {
Alan Viverettec078c602015-12-08 14:49:13 -05002435 try {
2436 if (TRACE_FOR_PRELOAD) {
2437 // Log only framework resources
2438 if ((id >>> 24) == 0x1) {
2439 final String name = getResourceName(id);
2440 if (name != null) {
2441 Log.d("PreloadDrawable", name);
2442 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445
Alan Viverettec078c602015-12-08 14:49:13 -05002446 final boolean isColorDrawable;
2447 final DrawableCache caches;
2448 final long key;
2449 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2450 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2451 isColorDrawable = true;
2452 caches = mColorDrawableCache;
2453 key = value.data;
2454 } else {
2455 isColorDrawable = false;
2456 caches = mDrawableCache;
2457 key = (((long) value.assetCookie) << 32) | value.data;
Alan Viverette52b999f2014-03-24 18:00:26 -07002458 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002459
Alan Viverettec078c602015-12-08 14:49:13 -05002460 // First, check whether we have a cached version of this drawable
Alan Viverette7941a7f2016-01-06 11:11:53 -05002461 // that was inflated against the specified theme. Skip the cache if
2462 // we're currently preloading or we're not using the cache.
2463 if (!mPreloading && useCache) {
Alan Viverettec078c602015-12-08 14:49:13 -05002464 final Drawable cachedDrawable = caches.getInstance(key, theme);
2465 if (cachedDrawable != null) {
2466 return cachedDrawable;
2467 }
2468 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002469
Alan Viverette7941a7f2016-01-06 11:11:53 -05002470 // Next, check preloaded drawables. Preloaded drawables may contain
2471 // unresolved theme attributes.
Alan Viverettec078c602015-12-08 14:49:13 -05002472 final ConstantState cs;
2473 if (isColorDrawable) {
2474 cs = sPreloadedColorDrawables.get(key);
2475 } else {
2476 cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2477 }
Alan Viverette4325f8e2015-04-01 15:00:30 -07002478
Alan Viverettec078c602015-12-08 14:49:13 -05002479 Drawable dr;
2480 if (cs != null) {
2481 dr = cs.newDrawable(this);
2482 } else if (isColorDrawable) {
2483 dr = new ColorDrawable(value.data);
2484 } else {
2485 dr = loadDrawableForCookie(value, id, null);
2486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487
Alan Viverettec078c602015-12-08 14:49:13 -05002488 // Determine if the drawable has unresolved theme attributes. If it
2489 // does, we'll need to apply a theme and store it in a theme-specific
2490 // cache.
2491 final boolean canApplyTheme = dr != null && dr.canApplyTheme();
2492 if (canApplyTheme && theme != null) {
2493 dr = dr.mutate();
2494 dr.applyTheme(theme);
2495 dr.clearMutated();
2496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497
Alan Viverettec078c602015-12-08 14:49:13 -05002498 // If we were able to obtain a drawable, store it in the appropriate
Alan Viverette7941a7f2016-01-06 11:11:53 -05002499 // cache: preload, not themed, null theme, or theme-specific. Don't
2500 // pollute the cache with drawables loaded from a foreign density.
2501 if (dr != null && useCache) {
Alan Viverettec078c602015-12-08 14:49:13 -05002502 dr.setChangingConfigurations(value.changingConfigurations);
2503 cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
2504 }
2505
2506 return dr;
2507 } catch (Exception e) {
2508 String name;
2509 try {
2510 name = getResourceName(id);
2511 } catch (NotFoundException e2) {
2512 name = "(missing name)";
2513 }
2514
2515 // The target drawable might fail to load for any number of
2516 // reasons, but we always want to include the resource name.
2517 // Since the client already expects this method to throw a
2518 // NotFoundException, just throw one of those.
2519 final NotFoundException nfe = new NotFoundException("Drawable " + name
2520 + " with resource ID #0x" + Integer.toHexString(id), e);
2521 nfe.setStackTrace(new StackTraceElement[0]);
2522 throw nfe;
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525
Alan Viverettee54d2452015-05-06 10:41:43 -07002526 private void cacheDrawable(TypedValue value, boolean isColorDrawable, DrawableCache caches,
2527 Theme theme, boolean usesTheme, long key, Drawable dr) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002528 final ConstantState cs = dr.getConstantState();
2529 if (cs == null) {
2530 return;
2531 }
2532
Alan Viverette52b999f2014-03-24 18:00:26 -07002533 if (mPreloading) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002534 final int changingConfigs = cs.getChangingConfigurations();
2535 if (isColorDrawable) {
2536 if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2537 sPreloadedColorDrawables.put(key, cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002539 } else {
2540 if (verifyPreloadConfig(
2541 changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2542 if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2543 // If this resource does not vary based on layout direction,
2544 // we can put it in all of the preload maps.
2545 sPreloadedDrawables[0].put(key, cs);
2546 sPreloadedDrawables[1].put(key, cs);
2547 } else {
2548 // Otherwise, only in the layout dir we loaded it for.
2549 sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 }
2552 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002553 } else {
2554 synchronized (mAccessLock) {
Alan Viverettee54d2452015-05-06 10:41:43 -07002555 caches.put(key, theme, cs, usesTheme);
Alan Viverette52b999f2014-03-24 18:00:26 -07002556 }
2557 }
2558 }
2559
2560 /**
2561 * Loads a drawable from XML or resources stream.
2562 */
2563 private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2564 if (value.string == null) {
Alan Viverette0810b632014-05-01 14:42:56 -07002565 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002566 + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
Alan Viverette52b999f2014-03-24 18:00:26 -07002567 }
2568
2569 final String file = value.string.toString();
2570
2571 if (TRACE_FOR_MISS_PRELOAD) {
2572 // Log only framework resources
2573 if ((id >>> 24) == 0x1) {
2574 final String name = getResourceName(id);
2575 if (name != null) {
2576 Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2577 + ": " + name + " at " + file);
2578 }
2579 }
2580 }
2581
2582 if (DEBUG_LOAD) {
2583 Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2584 }
2585
2586 final Drawable dr;
2587
2588 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2589 try {
2590 if (file.endsWith(".xml")) {
2591 final XmlResourceParser rp = loadXmlResourceParser(
2592 file, id, value.assetCookie, "drawable");
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002593 dr = Drawable.createFromXml(this, rp, theme);
Alan Viverette52b999f2014-03-24 18:00:26 -07002594 rp.close();
2595 } else {
2596 final InputStream is = mAssets.openNonAsset(
2597 value.assetCookie, file, AssetManager.ACCESS_STREAMING);
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002598 dr = Drawable.createFromResourceStream(this, value, is, file, null);
Alan Viverette52b999f2014-03-24 18:00:26 -07002599 is.close();
2600 }
2601 } catch (Exception e) {
2602 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2603 final NotFoundException rnf = new NotFoundException(
2604 "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2605 rnf.initCause(e);
2606 throw rnf;
2607 }
2608 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2609
2610 return dr;
2611 }
2612
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002613 /**
2614 * Given the value and id, we can get the XML filename as in value.data, based on that, we
2615 * first try to load CSL from the cache. If not found, try to get from the constant state.
2616 * Last, parse the XML and generate the CSL.
2617 */
2618 private ComplexColor loadComplexColorFromName(Theme theme, TypedValue value, int id) {
2619 final long key = (((long) value.assetCookie) << 32) | value.data;
2620 final ConfigurationBoundResourceCache<ComplexColor> cache = mComplexColorCache;
2621 ComplexColor complexColor = cache.getInstance(key, theme);
2622 if (complexColor != null) {
2623 return complexColor;
2624 }
2625
2626 final android.content.res.ConstantState<ComplexColor> factory =
2627 sPreloadedComplexColors.get(key);
2628
2629 if (factory != null) {
2630 complexColor = factory.newInstance(this, theme);
2631 }
2632 if (complexColor == null) {
2633 complexColor = loadComplexColorForCookie(value, id, theme);
2634 }
2635
2636 if (complexColor != null) {
2637 if (mPreloading) {
2638 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2639 "color")) {
2640 sPreloadedComplexColors.put(key, complexColor.getConstantState());
2641 }
2642 } else {
2643 cache.put(key, theme, complexColor.getConstantState());
2644 }
2645 }
2646 return complexColor;
2647 }
2648
2649 @Nullable
2650 public ComplexColor loadComplexColor(@NonNull TypedValue value, int id, Theme theme) {
2651 if (TRACE_FOR_PRELOAD) {
2652 // Log only framework resources
2653 if ((id >>> 24) == 0x1) {
2654 final String name = getResourceName(id);
2655 if (name != null) android.util.Log.d("loadComplexColor", name);
2656 }
2657 }
2658
2659 final long key = (((long) value.assetCookie) << 32) | value.data;
2660
2661 // Handle inline color definitions.
2662 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2663 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2664 return getColorStateListFromInt(value, key);
2665 }
2666
2667 final String file = value.string.toString();
2668
2669 ComplexColor complexColor;
2670 if (file.endsWith(".xml")) {
2671 try {
2672 complexColor = loadComplexColorFromName(theme, value, id);
2673 } catch (Exception e) {
2674 final NotFoundException rnf = new NotFoundException(
2675 "File " + file + " from complex color resource ID #0x"
2676 + Integer.toHexString(id));
2677 rnf.initCause(e);
2678 throw rnf;
2679 }
2680 } else {
2681 throw new NotFoundException(
2682 "File " + file + " from drawable resource ID #0x"
2683 + Integer.toHexString(id) + ": .xml extension required");
2684 }
2685
2686 return complexColor;
2687 }
2688
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002689 @Nullable
2690 ColorStateList loadColorStateList(TypedValue value, int id, Theme theme)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 throws NotFoundException {
2692 if (TRACE_FOR_PRELOAD) {
2693 // Log only framework resources
2694 if ((id >>> 24) == 0x1) {
2695 final String name = getResourceName(id);
2696 if (name != null) android.util.Log.d("PreloadColorStateList", name);
2697 }
2698 }
2699
Romain Guy5d911c32012-04-12 16:25:17 -07002700 final long key = (((long) value.assetCookie) << 32) | value.data;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002702 // Handle inline color definitions.
2703 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2704 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002705 return getColorStateListFromInt(value, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002708 ComplexColor complexColor = loadComplexColorFromName(theme, value, id);
2709 if (complexColor != null && complexColor instanceof ColorStateList) {
2710 return (ColorStateList) complexColor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002713 throw new NotFoundException(
2714 "Can't find ColorStateList from drawable resource ID #0x"
2715 + Integer.toHexString(id));
2716 }
2717
2718 @NonNull
2719 private ColorStateList getColorStateListFromInt(@NonNull TypedValue value, long key) {
2720 ColorStateList csl;
2721 final android.content.res.ConstantState<ComplexColor> factory =
2722 sPreloadedComplexColors.get(key);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002723 if (factory != null) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002724 return (ColorStateList) factory.newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 }
2726
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002727 csl = ColorStateList.valueOf(value.data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002728
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002729 if (mPreloading) {
2730 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2731 "color")) {
2732 sPreloadedComplexColors.put(key, csl.getConstantState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
2734 }
2735
2736 return csl;
2737 }
2738
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002739 /**
2740 * Load a ComplexColor based on the XML file content. The result can be a GradientColor or
2741 * ColorStateList. Note that pure color will be wrapped into a ColorStateList.
2742 *
2743 * We deferred the parser creation to this function b/c we need to differentiate b/t gradient
2744 * and selector tag.
2745 *
2746 * @return a ComplexColor (GradientColor or ColorStateList) based on the XML file content.
2747 */
2748 @Nullable
2749 private ComplexColor loadComplexColorForCookie(TypedValue value, int id, Theme theme) {
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002750 if (value.string == null) {
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002751 throw new UnsupportedOperationException(
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002752 "Can't convert to ComplexColor: type=0x" + value.type);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002753 }
2754
2755 final String file = value.string.toString();
2756
2757 if (TRACE_FOR_MISS_PRELOAD) {
2758 // Log only framework resources
2759 if ((id >>> 24) == 0x1) {
2760 final String name = getResourceName(id);
2761 if (name != null) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002762 Log.d(TAG, "Loading framework ComplexColor #" + Integer.toHexString(id)
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002763 + ": " + name + " at " + file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 }
2765 }
2766 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002767
2768 if (DEBUG_LOAD) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002769 Log.v(TAG, "Loading ComplexColor for cookie " + value.assetCookie + ": " + file);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002770 }
2771
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002772 ComplexColor complexColor = null;
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002773
2774 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2775 if (file.endsWith(".xml")) {
2776 try {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002777 final XmlResourceParser parser = loadXmlResourceParser(
2778 file, id, value.assetCookie, "ComplexColor");
2779
2780 final AttributeSet attrs = Xml.asAttributeSet(parser);
2781 int type;
2782 while ((type = parser.next()) != XmlPullParser.START_TAG
2783 && type != XmlPullParser.END_DOCUMENT) {
2784 // Seek parser to start tag.
2785 }
2786 if (type != XmlPullParser.START_TAG) {
2787 throw new XmlPullParserException("No start tag found");
2788 }
2789
2790 final String name = parser.getName();
2791 if (name.equals("gradient")) {
2792 complexColor = GradientColor.createFromXmlInner(this, parser, attrs, theme);
2793 } else if (name.equals("selector")) {
2794 complexColor = ColorStateList.createFromXmlInner(this, parser, attrs, theme);
2795 }
2796 parser.close();
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002797 } catch (Exception e) {
2798 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2799 final NotFoundException rnf = new NotFoundException(
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002800 "File " + file + " from ComplexColor resource ID #0x"
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002801 + Integer.toHexString(id));
2802 rnf.initCause(e);
2803 throw rnf;
2804 }
2805 } else {
2806 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2807 throw new NotFoundException(
2808 "File " + file + " from drawable resource ID #0x"
2809 + Integer.toHexString(id) + ": .xml extension required");
2810 }
2811 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2812
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002813 return complexColor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815
Alan Viverette10979612016-01-06 15:27:35 -05002816 /**
2817 * Loads an XML parser for the specified file.
2818 *
2819 * @param id the resource identifier for the file
2820 * @param type the type of resource (used for logging)
2821 * @return a parser for the specified XML file
2822 * @throws NotFoundException if the file could not be loaded
2823 */
2824 @NonNull
2825 XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05002827 final TypedValue value = obtainTempTypedValue(id);
2828 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if (value.type == TypedValue.TYPE_STRING) {
2830 return loadXmlResourceParser(value.string.toString(), id,
2831 value.assetCookie, type);
2832 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05002833 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
2834 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
2835 } finally {
2836 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 }
Alan Viverette10979612016-01-06 15:27:35 -05002839
2840 /**
2841 * Loads an XML parser for the specified file.
2842 *
2843 * @param file the path for the XML file to parse
2844 * @param id the resource identifier for the file
2845 * @param assetCookie the asset cookie for the file
2846 * @param type the type of resource (used for logging)
2847 * @return a parser for the specified XML file
2848 * @throws NotFoundException if the file could not be loaded
2849 */
2850 @NonNull
2851 XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id,
2852 int assetCookie, @NonNull String type) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 if (id != 0) {
2854 try {
Alan Viverette10979612016-01-06 15:27:35 -05002855 final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
2856 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
2857 synchronized (cachedXmlBlockFiles) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 // First see if this block is in our cache.
Alan Viverette10979612016-01-06 15:27:35 -05002859 final int num = cachedXmlBlockFiles.length;
2860 for (int i = 0; i < num; i++) {
2861 if (cachedXmlBlockFiles[i] != null
2862 && cachedXmlBlockFiles[i].equals(file)) {
2863 return cachedXmlBlocks[i].newParser();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 }
2865 }
2866
2867 // Not in the cache, create a new block and put it at
2868 // the next slot in the cache.
Alan Viverette10979612016-01-06 15:27:35 -05002869 final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 if (block != null) {
Alan Viverette10979612016-01-06 15:27:35 -05002871 final int pos = (mLastCachedXmlBlockIndex + 1) % num;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 mLastCachedXmlBlockIndex = pos;
Alan Viverette10979612016-01-06 15:27:35 -05002873 final XmlBlock oldBlock = cachedXmlBlocks[pos];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 if (oldBlock != null) {
2875 oldBlock.close();
2876 }
Alan Viverette10979612016-01-06 15:27:35 -05002877 cachedXmlBlockFiles[pos] = file;
2878 cachedXmlBlocks[pos] = block;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 return block.newParser();
2880 }
2881 }
2882 } catch (Exception e) {
Alan Viverette10979612016-01-06 15:27:35 -05002883 final NotFoundException rnf = new NotFoundException("File " + file
2884 + " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 rnf.initCause(e);
2886 throw rnf;
2887 }
2888 }
2889
Alan Viverette10979612016-01-06 15:27:35 -05002890 throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 + Integer.toHexString(id));
2892 }
2893
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002894 /**
2895 * Obtains styled attributes from the theme, if available, or unstyled
2896 * resources if the theme is null.
2897 *
2898 * @hide
2899 */
2900 public static TypedArray obtainAttributes(
2901 Resources res, Theme theme, AttributeSet set, int[] attrs) {
2902 if (theme == null) {
2903 return res.obtainAttributes(set, attrs);
2904 }
2905 return theme.obtainStyledAttributes(set, attrs, 0, 0);
2906 }
2907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 private Resources() {
2909 mAssets = AssetManager.getSystem();
Alan Viverette02fc5fe2015-08-27 13:16:09 -04002910 mClassLoader = ClassLoader.getSystemClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 // NOTE: Intentionally leaving this uninitialized (all values set
2912 // to zero), so that anyone who tries to do something that requires
2913 // metrics will get a very wrong value.
2914 mConfiguration.setToDefaults();
2915 mMetrics.setToDefaults();
2916 updateConfiguration(null, null);
2917 mAssets.ensureStringBlocks();
2918 }
2919}