blob: a54f40fc081471110b128b6861f17ef6f2e67e94 [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;
Alan Viverette5c64b952016-02-28 15:16:05 -050071import java.util.Arrays;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080072import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74/**
75 * Class for accessing an application's resources. This sits on top of the
Scott Mainf4f05b82011-01-07 14:38:23 -080076 * asset manager of the application (accessible through {@link #getAssets}) and
77 * provides a high-level API for getting typed data from the assets.
78 *
79 * <p>The Android resource system keeps track of all non-code assets associated with an
80 * application. You can use this class to access your application's resources. You can generally
81 * acquire the {@link android.content.res.Resources} instance associated with your application
82 * with {@link android.content.Context#getResources getResources()}.</p>
83 *
84 * <p>The Android SDK tools compile your application's resources into the application binary
85 * at build time. To use a resource, you must install it correctly in the source tree (inside
86 * your project's {@code res/} directory) and build your application. As part of the build
87 * process, the SDK tools generate symbols for each resource, which you can use in your application
88 * code to access the resources.</p>
89 *
90 * <p>Using application resources makes it easy to update various characteristics of your
91 * application without modifying code, and&mdash;by providing sets of alternative
92 * resources&mdash;enables you to optimize your application for a variety of device configurations
93 * (such as for different languages and screen sizes). This is an important aspect of developing
94 * Android applications that are compatible on different types of devices.</p>
95 *
96 * <p>For more information about using resources, see the documentation about <a
97 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 */
99public class Resources {
100 static final String TAG = "Resources";
Alan Viverette562a6a82014-01-31 11:07:29 -0800101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private static final boolean DEBUG_LOAD = false;
103 private static final boolean DEBUG_CONFIG = false;
104 private static final boolean TRACE_FOR_PRELOAD = false;
Dianne Hackborn9b44aae2011-09-02 19:17:16 -0700105 private static final boolean TRACE_FOR_MISS_PRELOAD = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
Alan Viverette562a6a82014-01-31 11:07:29 -0800107 private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative(
108 ActivityInfo.CONFIG_LAYOUT_DIRECTION);
109
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700110 private static final int ID_OTHER = 0x01000004;
111
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800112 private static final Object sSync = new Object();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 // Information about preloaded resources. Note that they are not
115 // protected by a lock, because while preloading in zygote we are all
116 // single-threaded, and after that these are immutable.
Alan Viverette52b999f2014-03-24 18:00:26 -0700117 private static final LongSparseArray<ConstantState>[] sPreloadedDrawables;
118 private static final LongSparseArray<ConstantState> sPreloadedColorDrawables
Alan Viverettea8636c92015-03-27 10:44:39 -0700119 = new LongSparseArray<>();
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -0800120 private static final LongSparseArray<android.content.res.ConstantState<ComplexColor>>
121 sPreloadedComplexColors = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700122
Alan Viverette5c64b952016-02-28 15:16:05 -0500123 /** Size of the cyclical cache used to map XML files to blocks. */
124 private static final int XML_BLOCK_CACHE_SIZE = 4;
125
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700126 // Pool of TypedArrays targeted to this Resources object.
Alan Viverettea8636c92015-03-27 10:44:39 -0700127 final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700128
Alan Viveretteedc46642014-02-01 01:43:16 -0800129 // Used by BridgeResources in layoutlib
130 static Resources mSystem = null;
131
Dianne Hackborndde331c2012-08-03 14:01:57 -0700132 private static boolean sPreloaded;
Alan Viverette4d07bc92015-11-16 10:19:12 -0500133
134 /** Lock object used to protect access to caches and configuration. */
135 private final Object mAccessLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800137 // These are protected by mAccessLock.
Alan Viverette562a6a82014-01-31 11:07:29 -0800138 private final Configuration mTmpConfig = new Configuration();
Alan Viverettee54d2452015-05-06 10:41:43 -0700139 private final DrawableCache mDrawableCache = new DrawableCache(this);
140 private final DrawableCache mColorDrawableCache = new DrawableCache(this);
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -0800141 private final ConfigurationBoundResourceCache<ComplexColor> mComplexColorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700142 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700143 private final ConfigurationBoundResourceCache<Animator> mAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700144 new ConfigurationBoundResourceCache<>(this);
Yigit Boyard422dc32014-09-25 12:23:35 -0700145 private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache =
Alan Viverettea8636c92015-03-27 10:44:39 -0700146 new ConfigurationBoundResourceCache<>(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400148 /** Used to inflate drawable objects from XML. */
149 private DrawableInflater mDrawableInflater;
150
Alan Viverette4d07bc92015-11-16 10:19:12 -0500151 /** Lock object used to protect access to {@link #mTmpValue}. */
152 private final Object mTmpValueLock = new Object();
153
154 /** Single-item pool used to minimize TypedValue allocations. */
Alan Viverette562a6a82014-01-31 11:07:29 -0800155 private TypedValue mTmpValue = new TypedValue();
Alan Viverette4d07bc92015-11-16 10:19:12 -0500156
Alan Viverette562a6a82014-01-31 11:07:29 -0800157 private boolean mPreloading;
158
Alan Viverette10979612016-01-06 15:27:35 -0500159 // Cyclical cache used for recently-accessed XML files.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mLastCachedXmlBlockIndex = -1;
Alan Viverette5c64b952016-02-28 15:16:05 -0500161 private final int[] mCachedXmlBlockCookies = new int[XML_BLOCK_CACHE_SIZE];
162 private final String[] mCachedXmlBlockFiles = new String[XML_BLOCK_CACHE_SIZE];
163 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[XML_BLOCK_CACHE_SIZE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700165 final AssetManager mAssets;
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400166 final ClassLoader mClassLoader;
Alan Viverette8b5b25b2014-09-13 19:30:11 -0700167 final DisplayMetrics mMetrics = new DisplayMetrics();
168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 private final Configuration mConfiguration = new Configuration();
Raph Levien1f0945e2016-01-20 12:16:50 -0800170
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100171 private PluralRules mPluralRule;
Craig Mautner48d0d182013-06-11 07:53:06 -0700172
173 private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
Alan Viverette52b999f2014-03-24 18:00:26 -0700174
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700175 static {
176 sPreloadedDrawables = new LongSparseArray[2];
Alan Viverettea8636c92015-03-27 10:44:39 -0700177 sPreloadedDrawables[0] = new LongSparseArray<>();
178 sPreloadedDrawables[1] = new LongSparseArray<>();
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -0700179 }
180
Alan Viverette62599332014-04-01 14:57:39 -0700181 /**
182 * Returns the most appropriate default theme for the specified target SDK version.
Alan Viverette5effd7e2014-05-05 12:25:33 -0700183 * <ul>
184 * <li>Below API 11: Gingerbread
185 * <li>APIs 11 thru 14: Holo
186 * <li>APIs 14 thru XX: Device default dark
187 * <li>API XX and above: Device default light with dark action bar
188 * </ul>
Alan Viverette62599332014-04-01 14:57:39 -0700189 *
190 * @param curTheme The current theme, or 0 if not specified.
191 * @param targetSdkVersion The target SDK version.
192 * @return A theme resource identifier
193 * @hide
194 */
Alan Viverette5effd7e2014-05-05 12:25:33 -0700195 public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800196 return selectSystemTheme(curTheme, targetSdkVersion,
Alan Viverette5effd7e2014-05-05 12:25:33 -0700197 com.android.internal.R.style.Theme,
198 com.android.internal.R.style.Theme_Holo,
199 com.android.internal.R.style.Theme_DeviceDefault,
200 com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar);
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800201 }
Alan Viverette62599332014-04-01 14:57:39 -0700202
Alan Viverette5effd7e2014-05-05 12:25:33 -0700203 /** @hide */
204 public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo,
205 int dark, int deviceDefault) {
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800206 if (curTheme != 0) {
207 return curTheme;
208 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700209 if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) {
210 return orig;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800211 }
Alan Viverette5effd7e2014-05-05 12:25:33 -0700212 if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
213 return holo;
214 }
215 if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) {
216 return dark;
217 }
218 return deviceDefault;
Dianne Hackbornd922ae02011-01-14 11:43:24 -0800219 }
Alan Viverette62599332014-04-01 14:57:39 -0700220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 /**
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400222 * @return the inflater used to create drawable objects
223 * @hide Pending API finalization.
224 */
225 public final DrawableInflater getDrawableInflater() {
226 if (mDrawableInflater == null) {
227 mDrawableInflater = new DrawableInflater(this, mClassLoader);
228 }
229 return mDrawableInflater;
230 }
231
232 /**
Yigit Boyard422dc32014-09-25 12:23:35 -0700233 * Used by AnimatorInflater.
234 *
235 * @hide
236 */
237 public ConfigurationBoundResourceCache<Animator> getAnimatorCache() {
238 return mAnimatorCache;
239 }
240
241 /**
242 * Used by AnimatorInflater.
243 *
244 * @hide
245 */
246 public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
247 return mStateListAnimatorCache;
248 }
249
250 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 * This exception is thrown by the resource APIs when a requested resource
252 * can not be found.
253 */
254 public static class NotFoundException extends RuntimeException {
255 public NotFoundException() {
256 }
257
258 public NotFoundException(String name) {
259 super(name);
260 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500261
262 public NotFoundException(String name, Exception cause) {
263 super(name, cause);
264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266
267 /**
268 * Create a new Resources object on top of an existing set of assets in an
269 * AssetManager.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800270 *
271 * @param assets Previously created AssetManager.
272 * @param metrics Current display metrics to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800274 * @param config Desired device configuration to consider when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 * selecting/computing resource values (optional).
276 */
Romain Guy5d911c32012-04-12 16:25:17 -0700277 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400278 this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700279 }
280
281 /**
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -0700282 * Creates a new Resources object with CompatibilityInfo.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800283 *
284 * @param assets Previously created AssetManager.
285 * @param metrics Current display metrics to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700286 * selecting/computing resource values.
Wale Ogunwale60454db2015-01-23 16:05:07 -0800287 * @param config Desired device configuration to consider when
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700288 * selecting/computing resource values (optional).
Craig Mautner48d0d182013-06-11 07:53:06 -0700289 * @param compatInfo this resource's compatibility info. Must not be null.
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400290 * @param classLoader class loader for the package used to load custom
291 * resource classes, may be {@code null} to use system
292 * class loader
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700293 * @hide
294 */
Craig Mautner48d0d182013-06-11 07:53:06 -0700295 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400296 CompatibilityInfo compatInfo, @Nullable ClassLoader classLoader) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 mAssets = assets;
Alan Viverette02fc5fe2015-08-27 13:16:09 -0400298 mClassLoader = classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 mMetrics.setToDefaults();
Adam Lesinski79a8ffe2013-09-19 20:33:15 -0700300 if (compatInfo != null) {
301 mCompatibilityInfo = compatInfo;
302 }
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700303 updateConfiguration(config, metrics);
304 assets.ensureStringBlocks();
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700305 }
306
307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * Return a global shared Resources object that provides access to only
Wale Ogunwale60454db2015-01-23 16:05:07 -0800309 * system resources (no application resources), and is not configured for
310 * the current screen (can not use dimension units, does not change based
311 * on orientation, etc).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 */
313 public static Resources getSystem() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800314 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 Resources ret = mSystem;
316 if (ret == null) {
317 ret = new Resources();
318 mSystem = ret;
319 }
320
321 return ret;
322 }
323 }
324
325 /**
326 * Return the string value associated with a particular resource ID. The
327 * returned object will be a String if this is a plain string; it will be
328 * some other type of CharSequence if it is styled.
329 * {@more}
330 *
331 * @param id The desired resource identifier, as generated by the aapt
332 * tool. This integer encodes the package, type, and resource
333 * entry. The value 0 is an invalid identifier.
334 *
335 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
336 *
337 * @return CharSequence The string data associated with the resource, plus
338 * possibly styled text information.
339 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700340 public CharSequence getText(@StringRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 CharSequence res = mAssets.getResourceText(id);
342 if (res != null) {
343 return res;
344 }
345 throw new NotFoundException("String resource ID #0x"
346 + Integer.toHexString(id));
347 }
348
349 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800350 * Returns the character sequence necessary for grammatically correct pluralization
351 * of the given resource ID for the given quantity.
352 * Note that the character sequence is selected based solely on grammatical necessity,
353 * and that such rules differ between languages. Do not assume you know which string
354 * will be returned for a given quantity. See
355 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
356 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700357 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * @param id The desired resource identifier, as generated by the aapt
359 * tool. This integer encodes the package, type, and resource
360 * entry. The value 0 is an invalid identifier.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700361 * @param quantity The number used to get the correct string for the current language's
362 * plural rules.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 *
364 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
365 *
366 * @return CharSequence The string data associated with the resource, plus
367 * possibly styled text information.
368 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700369 public CharSequence getQuantityText(@PluralsRes int id, int quantity)
370 throws NotFoundException {
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100371 PluralRules rule = getPluralRule();
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700372 CharSequence res = mAssets.getResourceBagText(id,
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100373 attrForQuantityCode(rule.select(quantity)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 if (res != null) {
375 return res;
376 }
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700377 res = mAssets.getResourceBagText(id, ID_OTHER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 if (res != null) {
379 return res;
380 }
381 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id)
382 + " quantity=" + quantity
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100383 + " item=" + rule.select(quantity));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100386 private PluralRules getPluralRule() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800387 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 if (mPluralRule == null) {
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800389 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
391 return mPluralRule;
392 }
393 }
394
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100395 private static int attrForQuantityCode(String quantityCode) {
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700396 switch (quantityCode) {
Rayhaan Jaufeerallyb27b3052015-07-15 15:25:15 +0100397 case PluralRules.KEYWORD_ZERO: return 0x01000005;
398 case PluralRules.KEYWORD_ONE: return 0x01000006;
399 case PluralRules.KEYWORD_TWO: return 0x01000007;
400 case PluralRules.KEYWORD_FEW: return 0x01000008;
401 case PluralRules.KEYWORD_MANY: return 0x01000009;
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700402 default: return ID_OTHER;
403 }
404 }
405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 /**
407 * Return the string value associated with a particular resource ID. It
408 * will be stripped of any styled text information.
409 * {@more}
410 *
411 * @param id The desired resource identifier, as generated by the aapt
412 * tool. This integer encodes the package, type, and resource
413 * entry. The value 0 is an invalid identifier.
414 *
415 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
416 *
417 * @return String The string data associated with the resource,
Alan Viveretteb4004df2015-04-29 16:55:42 -0700418 * stripped of styled text information.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 */
Alan Viveretteb4004df2015-04-29 16:55:42 -0700420 @NonNull
Tor Norbye7b9c9122013-05-30 16:48:33 -0700421 public String getString(@StringRes int id) throws NotFoundException {
Alan Viveretteb4004df2015-04-29 16:55:42 -0700422 final CharSequence res = getText(id);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 if (res != null) {
424 return res.toString();
425 }
426 throw new NotFoundException("String resource ID #0x"
427 + Integer.toHexString(id));
428 }
429
430
431 /**
432 * Return the string value associated with a particular resource ID,
433 * substituting the format arguments as defined in {@link java.util.Formatter}
434 * and {@link java.lang.String#format}. It will be stripped of any styled text
435 * information.
436 * {@more}
437 *
438 * @param id The desired resource identifier, as generated by the aapt
439 * tool. This integer encodes the package, type, and resource
440 * entry. The value 0 is an invalid identifier.
441 *
442 * @param formatArgs The format arguments that will be used for substitution.
443 *
444 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
445 *
446 * @return String The string data associated with the resource,
Alan Viveretteb4004df2015-04-29 16:55:42 -0700447 * stripped of styled text information.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 */
Alan Viveretteb4004df2015-04-29 16:55:42 -0700449 @NonNull
450 public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
451 final String raw = getString(id);
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800452 return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454
455 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800456 * Formats the string necessary for grammatically correct pluralization
457 * of the given resource ID for the given quantity, using the given arguments.
458 * Note that the string is selected based solely on grammatical necessity,
459 * and that such rules differ between languages. Do not assume you know which string
460 * will be returned for a given quantity. See
461 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
462 * for more detail.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 *
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800464 * <p>Substitution of format arguments works as if using
465 * {@link java.util.Formatter} and {@link java.lang.String#format}.
466 * The resulting string will be stripped of any styled text information.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700467 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 * @param id The desired resource identifier, as generated by the aapt
469 * tool. This integer encodes the package, type, and resource
470 * entry. The value 0 is an invalid identifier.
471 * @param quantity The number used to get the correct string for the current language's
472 * plural rules.
473 * @param formatArgs The format arguments that will be used for substitution.
474 *
475 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
476 *
477 * @return String The string data associated with the resource,
478 * stripped of styled text information.
479 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700480 public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 throws NotFoundException {
482 String raw = getQuantityText(id, quantity).toString();
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800483 return String.format(mConfiguration.getLocales().get(0), raw, formatArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
485
486 /**
Elliott Hughes95d5ab32013-03-08 11:26:57 -0800487 * Returns the string necessary for grammatically correct pluralization
488 * of the given resource ID for the given quantity.
489 * Note that the string is selected based solely on grammatical necessity,
490 * and that such rules differ between languages. Do not assume you know which string
491 * will be returned for a given quantity. See
492 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a>
493 * for more detail.
Elliott Hughes1ad636c2010-07-01 16:51:48 -0700494 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 * @param id The desired resource identifier, as generated by the aapt
496 * tool. This integer encodes the package, type, and resource
497 * entry. The value 0 is an invalid identifier.
498 * @param quantity The number used to get the correct string for the current language's
499 * plural rules.
500 *
501 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
502 *
503 * @return String The string data associated with the resource,
504 * stripped of styled text information.
505 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700506 public String getQuantityString(@PluralsRes int id, int quantity)
507 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 return getQuantityText(id, quantity).toString();
509 }
510
511 /**
512 * Return the string value associated with a particular resource ID. The
513 * returned object will be a String if this is a plain string; it will be
514 * some other type of CharSequence if it is styled.
515 *
516 * @param id The desired resource identifier, as generated by the aapt
517 * tool. This integer encodes the package, type, and resource
518 * entry. The value 0 is an invalid identifier.
519 *
520 * @param def The default CharSequence to return.
521 *
522 * @return CharSequence The string data associated with the resource, plus
523 * possibly styled text information, or def if id is 0 or not found.
524 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700525 public CharSequence getText(@StringRes int id, CharSequence def) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 CharSequence res = id != 0 ? mAssets.getResourceText(id) : null;
527 return res != null ? res : def;
528 }
529
530 /**
531 * Return the styled text array associated with a particular resource ID.
532 *
533 * @param id The desired resource identifier, as generated by the aapt
534 * tool. This integer encodes the package, type, and resource
535 * entry. The value 0 is an invalid identifier.
536 *
537 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
538 *
539 * @return The styled text array associated with the resource.
540 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700541 public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 CharSequence[] res = mAssets.getResourceTextArray(id);
543 if (res != null) {
544 return res;
545 }
546 throw new NotFoundException("Text array resource ID #0x"
547 + Integer.toHexString(id));
548 }
549
550 /**
551 * Return the string array associated with a particular resource ID.
552 *
553 * @param id The desired resource identifier, as generated by the aapt
554 * tool. This integer encodes the package, type, and resource
555 * entry. The value 0 is an invalid identifier.
556 *
557 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
558 *
559 * @return The string array associated with the resource.
560 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700561 public String[] getStringArray(@ArrayRes int id)
562 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 String[] res = mAssets.getResourceStringArray(id);
564 if (res != null) {
565 return res;
566 }
567 throw new NotFoundException("String array resource ID #0x"
568 + Integer.toHexString(id));
569 }
570
571 /**
572 * Return the int array associated with a particular resource ID.
573 *
574 * @param id The desired resource identifier, as generated by the aapt
575 * tool. This integer encodes the package, type, and resource
576 * entry. The value 0 is an invalid identifier.
577 *
578 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
579 *
580 * @return The int array associated with the resource.
581 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700582 public int[] getIntArray(@ArrayRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 int[] res = mAssets.getArrayIntResource(id);
584 if (res != null) {
585 return res;
586 }
587 throw new NotFoundException("Int array resource ID #0x"
588 + Integer.toHexString(id));
589 }
590
591 /**
592 * Return an array of heterogeneous values.
593 *
594 * @param id The desired resource identifier, as generated by the aapt
595 * tool. This integer encodes the package, type, and resource
596 * entry. The value 0 is an invalid identifier.
597 *
598 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
599 *
600 * @return Returns a TypedArray holding an array of the array values.
601 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
602 * when done with it.
603 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700604 public TypedArray obtainTypedArray(@ArrayRes int id)
605 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 int len = mAssets.getArraySize(id);
607 if (len < 0) {
608 throw new NotFoundException("Array resource ID #0x"
609 + Integer.toHexString(id));
610 }
611
Alan Viverette52b999f2014-03-24 18:00:26 -0700612 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 array.mLength = mAssets.retrieveArray(id, array.mData);
614 array.mIndices[0] = 0;
615
616 return array;
617 }
618
619 /**
620 * Retrieve a dimensional for a particular resource ID. Unit
621 * conversions are based on the current {@link DisplayMetrics} associated
622 * with the resources.
623 *
624 * @param id The desired resource identifier, as generated by the aapt
625 * tool. This integer encodes the package, type, and resource
626 * entry. The value 0 is an invalid identifier.
627 *
628 * @return Resource dimension value multiplied by the appropriate
629 * metric.
630 *
631 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
632 *
633 * @see #getDimensionPixelOffset
634 * @see #getDimensionPixelSize
635 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700636 public float getDimension(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500637 final TypedValue value = obtainTempTypedValue(id);
638 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 if (value.type == TypedValue.TYPE_DIMENSION) {
640 return TypedValue.complexToDimension(value.data, mMetrics);
641 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500642 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
643 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
644 } finally {
645 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647 }
648
649 /**
650 * Retrieve a dimensional for a particular resource ID for use
651 * as an offset in raw pixels. This is the same as
652 * {@link #getDimension}, except the returned value is converted to
653 * integer pixels for you. An offset conversion involves simply
654 * truncating the base value to an integer.
655 *
656 * @param id The desired resource identifier, as generated by the aapt
657 * tool. This integer encodes the package, type, and resource
658 * entry. The value 0 is an invalid identifier.
659 *
660 * @return Resource dimension value multiplied by the appropriate
661 * metric and truncated to integer pixels.
662 *
663 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
664 *
665 * @see #getDimension
666 * @see #getDimensionPixelSize
667 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700668 public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500669 final TypedValue value = obtainTempTypedValue(id);
670 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 if (value.type == TypedValue.TYPE_DIMENSION) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500672 return TypedValue.complexToDimensionPixelOffset(value.data, mMetrics);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500674 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
675 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
676 } finally {
677 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
679 }
680
681 /**
682 * Retrieve a dimensional for a particular resource ID for use
683 * as a size in raw pixels. This is the same as
684 * {@link #getDimension}, except the returned value is converted to
685 * integer pixels for use as a size. A size conversion involves
686 * rounding the base value, and ensuring that a non-zero base value
687 * is at least one pixel in size.
688 *
689 * @param id The desired resource identifier, as generated by the aapt
690 * tool. This integer encodes the package, type, and resource
691 * entry. The value 0 is an invalid identifier.
692 *
693 * @return Resource dimension value multiplied by the appropriate
694 * metric and truncated to integer pixels.
695 *
696 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
697 *
698 * @see #getDimension
699 * @see #getDimensionPixelOffset
700 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700701 public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500702 final TypedValue value = obtainTempTypedValue(id);
703 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 if (value.type == TypedValue.TYPE_DIMENSION) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500705 return TypedValue.complexToDimensionPixelSize(value.data, mMetrics);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500707 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
708 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
709 } finally {
710 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712 }
713
714 /**
715 * Retrieve a fractional unit for a particular resource ID.
716 *
717 * @param id The desired resource identifier, as generated by the aapt
718 * tool. This integer encodes the package, type, and resource
719 * entry. The value 0 is an invalid identifier.
720 * @param base The base value of this fraction. In other words, a
721 * standard fraction is multiplied by this value.
722 * @param pbase The parent base value of this fraction. In other
723 * words, a parent fraction (nn%p) is multiplied by this
724 * value.
725 *
726 * @return Attribute fractional value multiplied by the appropriate
727 * base value.
728 *
729 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
730 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700731 public float getFraction(@FractionRes int id, int base, int pbase) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500732 final TypedValue value = obtainTempTypedValue(id);
733 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 if (value.type == TypedValue.TYPE_FRACTION) {
735 return TypedValue.complexToFraction(value.data, base, pbase);
736 }
Alan Viverette4d07bc92015-11-16 10:19:12 -0500737 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
738 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
739 } finally {
740 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 }
742 }
743
744 /**
745 * Return a drawable object associated with a particular resource ID.
746 * Various types of objects will be returned depending on the underlying
747 * resource -- for example, a solid color, PNG image, scalable image, etc.
748 * The Drawable API hides these implementation details.
Dianne Hackbornfb5c3db2012-05-18 15:24:24 -0700749 *
750 * <p class="note"><strong>Note:</strong> Prior to
751 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function
752 * would not correctly retrieve the final configuration density when
753 * the resource ID passed here is an alias to another Drawable resource.
754 * This means that if the density configuration of the alias resource
755 * is different than the actual resource, the density of the returned
756 * Drawable would be incorrect, resulting in bad scaling. To work
757 * around this, you can instead retrieve the Drawable through
758 * {@link TypedArray#getDrawable TypedArray.getDrawable}. Use
759 * {@link android.content.Context#obtainStyledAttributes(int[])
760 * Context.obtainStyledAttributes} with
761 * an array containing the resource ID of interest to create the TypedArray.</p>
762 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700763 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
764 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
765 * or {@link #getDrawable(int, Theme)} passing the desired theme.</p>
766 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 * @param id The desired resource identifier, as generated by the aapt
768 * tool. This integer encodes the package, type, and resource
769 * entry. The value 0 is an invalid identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 * @return Drawable An object that can be used to draw this resource.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800771 * @throws NotFoundException Throws NotFoundException if the given ID does
772 * not exist.
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700773 * @see #getDrawable(int, Theme)
Alan Viverettec10e3962014-12-02 14:58:08 -0800774 * @deprecated Use {@link #getDrawable(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 */
Alan Viverettec10e3962014-12-02 14:58:08 -0800776 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700777 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette34a14f962014-08-15 16:13:15 -0700778 final Drawable d = getDrawable(id, null);
Alan Viverette7e0aaae2014-11-24 11:27:09 -0800779 if (d != null && d.canApplyTheme()) {
Alan Viverette34a14f962014-08-15 16:13:15 -0700780 Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
781 + "attributes! Consider using Resources.getDrawable(int, Theme) or "
782 + "Context.getDrawable(int).", new RuntimeException());
783 }
784 return d;
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800785 }
786
787 /**
788 * Return a drawable object associated with a particular resource ID and
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700789 * styled for the specified theme. Various types of objects will be
790 * returned depending on the underlying resource -- for example, a solid
791 * color, PNG image, scalable image, etc.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800792 *
793 * @param id The desired resource identifier, as generated by the aapt
794 * tool. This integer encodes the package, type, and resource
795 * entry. The value 0 is an invalid identifier.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700796 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800797 * @return Drawable An object that can be used to draw this resource.
798 * @throws NotFoundException Throws NotFoundException if the given ID does
799 * not exist.
800 */
Alan Viverette4d07bc92015-11-16 10:19:12 -0500801 public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
802 throws NotFoundException {
803 final TypedValue value = obtainTempTypedValue(id);
804 try {
805 return loadDrawable(value, id, theme);
806 } finally {
807 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 }
810
811 /**
Kenny Root55fc8502010-10-28 14:47:01 -0700812 * Return a drawable object associated with a particular resource ID for the
813 * given screen density in DPI. This will set the drawable's density to be
814 * the device's density multiplied by the ratio of actual drawable density
815 * to requested density. This allows the drawable to be scaled up to the
816 * correct size if needed. Various types of objects will be returned
817 * depending on the underlying resource -- for example, a solid color, PNG
818 * image, scalable image, etc. The Drawable API hides these implementation
819 * details.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800820 *
Alan Viverette6dbe51b2014-06-02 16:39:04 -0700821 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use
822 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)}
823 * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired
824 * theme.</p>
825 *
Kenny Root55fc8502010-10-28 14:47:01 -0700826 * @param id The desired resource identifier, as generated by the aapt tool.
827 * This integer encodes the package, type, and resource entry.
828 * The value 0 is an invalid identifier.
829 * @param density the desired screen density indicated by the resource as
830 * found in {@link DisplayMetrics}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800831 * @return Drawable An object that can be used to draw this resource.
Kenny Root55fc8502010-10-28 14:47:01 -0700832 * @throws NotFoundException Throws NotFoundException if the given ID does
833 * not exist.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800834 * @see #getDrawableForDensity(int, int, Theme)
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800835 * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead.
Kenny Root55fc8502010-10-28 14:47:01 -0700836 */
Alan Viverettea6f8b2c2014-12-02 15:26:33 -0800837 @Deprecated
Alan Viverette4d07bc92015-11-16 10:19:12 -0500838 public Drawable getDrawableForDensity(@DrawableRes int id, int density)
839 throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800840 return getDrawableForDensity(id, density, null);
841 }
842
843 /**
844 * Return a drawable object associated with a particular resource ID for the
845 * given screen density in DPI and styled for the specified theme.
846 *
847 * @param id The desired resource identifier, as generated by the aapt tool.
848 * This integer encodes the package, type, and resource entry.
849 * The value 0 is an invalid identifier.
850 * @param density The desired screen density indicated by the resource as
851 * found in {@link DisplayMetrics}.
Alan Viverette3b5c4272014-05-20 13:20:42 -0700852 * @param theme The theme used to style the drawable attributes, may be {@code null}.
Alan Viverette8eea3ea2014-02-03 18:40:20 -0800853 * @return Drawable An object that can be used to draw this resource.
854 * @throws NotFoundException Throws NotFoundException if the given ID does
855 * not exist.
856 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700857 public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500858 final TypedValue value = obtainTempTypedValue(id);
859 try {
Kenny Root55fc8502010-10-28 14:47:01 -0700860 getValueForDensity(id, density, value, true);
861
Alan Viverette7941a7f2016-01-06 11:11:53 -0500862 // If the drawable's XML lives in our current density qualifier,
863 // it's okay to use a scaled version from the cache. Otherwise, we
864 // need to actually load the drawable from XML.
865 final boolean useCache = value.density == mMetrics.densityDpi;
866
Kenny Root55fc8502010-10-28 14:47:01 -0700867 /*
868 * Pretend the requested density is actually the display density. If
869 * the drawable returned is not the requested density, then force it
870 * to be scaled later by dividing its density by the ratio of
871 * requested density to actual device density. Drawables that have
872 * undefined density or no density don't need to be handled here.
873 */
874 if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
875 if (value.density == density) {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700876 value.density = mMetrics.densityDpi;
Kenny Root55fc8502010-10-28 14:47:01 -0700877 } else {
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700878 value.density = (value.density * mMetrics.densityDpi) / density;
Kenny Root55fc8502010-10-28 14:47:01 -0700879 }
880 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800881
Alan Viverette7941a7f2016-01-06 11:11:53 -0500882 return loadDrawable(value, id, theme, useCache);
Alan Viverette4d07bc92015-11-16 10:19:12 -0500883 } finally {
884 releaseTempTypedValue(value);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800885 }
Kenny Root55fc8502010-10-28 14:47:01 -0700886 }
887
888 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 * Return a movie object associated with the particular resource ID.
890 * @param id The desired resource identifier, as generated by the aapt
891 * tool. This integer encodes the package, type, and resource
892 * entry. The value 0 is an invalid identifier.
893 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
894 *
895 */
Tor Norbye7b9c9122013-05-30 16:48:33 -0700896 public Movie getMovie(@RawRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 InputStream is = openRawResource(id);
898 Movie movie = Movie.decodeStream(is);
899 try {
900 is.close();
901 }
902 catch (java.io.IOException e) {
903 // don't care, since the return value is valid
904 }
905 return movie;
906 }
907
908 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800909 * Returns a color integer associated with a particular resource ID. If the
910 * resource holds a complex {@link ColorStateList}, then the default color
911 * from the set is returned.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 *
913 * @param id The desired resource identifier, as generated by the aapt
914 * tool. This integer encodes the package, type, and resource
915 * entry. The value 0 is an invalid identifier.
916 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800917 * @throws NotFoundException Throws NotFoundException if the given ID does
918 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800920 * @return A single color value in the form 0xAARRGGBB.
921 * @deprecated Use {@link #getColor(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 */
Tor Norbye80756e32015-03-02 09:39:27 -0800923 @ColorInt
Alan Viverette4a357cd2015-03-18 18:37:18 -0700924 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700925 public int getColor(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800926 return getColor(id, null);
927 }
928
929 /**
930 * Returns a themed color integer associated with a particular resource ID.
931 * If the resource holds a complex {@link ColorStateList}, then the default
932 * color from the set is returned.
933 *
934 * @param id The desired resource identifier, as generated by the aapt
935 * tool. This integer encodes the package, type, and resource
936 * entry. The value 0 is an invalid identifier.
937 * @param theme The theme used to style the color attributes, may be
938 * {@code null}.
939 *
940 * @throws NotFoundException Throws NotFoundException if the given ID does
941 * not exist.
942 *
943 * @return A single color value in the form 0xAARRGGBB.
944 */
Tor Norbye80756e32015-03-02 09:39:27 -0800945 @ColorInt
Tor Norbye7b9c9122013-05-30 16:48:33 -0700946 public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500947 final TypedValue value = obtainTempTypedValue(id);
948 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800950 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 return value.data;
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800952 } else if (value.type != TypedValue.TYPE_STRING) {
Alan Viverette4d07bc92015-11-16 10:19:12 -0500953 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
954 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800956
Alan Viverette4d07bc92015-11-16 10:19:12 -0500957 final ColorStateList csl = loadColorStateList(value, id, theme);
958 return csl.getDefaultColor();
959 } finally {
960 releaseTempTypedValue(value);
Dianne Hackborn50707cc2013-02-08 15:32:05 -0800961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963
964 /**
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800965 * Returns a color state list associated with a particular resource ID. The
966 * resource may contain either a single raw color value or a complex
967 * {@link ColorStateList} holding multiple possible colors.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 *
969 * @param id The desired resource identifier of a {@link ColorStateList},
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800970 * as generated by the aapt tool. This integer encodes the
971 * package, type, and resource entry. The value 0 is an invalid
972 * identifier.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800974 * @throws NotFoundException Throws NotFoundException if the given ID does
975 * not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 *
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800977 * @return A ColorStateList object containing either a single solid color
978 * or multiple colors that can be selected based on a state.
979 * @deprecated Use {@link #getColorStateList(int, Theme)} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 */
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800981 @Nullable
Alan Viverette4a357cd2015-03-18 18:37:18 -0700982 @Deprecated
Tor Norbye7b9c9122013-05-30 16:48:33 -0700983 public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException {
Alan Viverette45c4bbb2015-01-05 14:59:19 -0800984 final ColorStateList csl = getColorStateList(id, null);
985 if (csl != null && csl.canApplyTheme()) {
986 Log.w(TAG, "ColorStateList " + getResourceName(id) + " has "
987 + "unresolved theme attributes! Consider using "
988 + "Resources.getColorStateList(int, Theme) or "
989 + "Context.getColorStateList(int).", new RuntimeException());
990 }
991 return csl;
992 }
993
994 /**
995 * Returns a themed color state list associated with a particular resource
996 * ID. The resource may contain either a single raw color value or a
997 * complex {@link ColorStateList} holding multiple possible colors.
998 *
999 * @param id The desired resource identifier of a {@link ColorStateList},
1000 * as generated by the aapt tool. This integer encodes the
1001 * package, type, and resource entry. The value 0 is an invalid
1002 * identifier.
1003 * @param theme The theme used to style the color attributes, may be
1004 * {@code null}.
1005 *
1006 * @throws NotFoundException Throws NotFoundException if the given ID does
1007 * not exist.
1008 *
1009 * @return A themed ColorStateList object containing either a single solid
1010 * color or multiple colors that can be selected based on a state.
1011 */
1012 @Nullable
Tor Norbye7b9c9122013-05-30 16:48:33 -07001013 public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme)
Alan Viverette45c4bbb2015-01-05 14:59:19 -08001014 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001015 final TypedValue value = obtainTempTypedValue(id);
1016 try {
1017 return loadColorStateList(value, id, theme);
1018 } finally {
1019 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021 }
1022
1023 /**
1024 * Return a boolean associated with a particular resource ID. This can be
1025 * used with any integral resource value, and will return true if it is
1026 * non-zero.
1027 *
1028 * @param id The desired resource identifier, as generated by the aapt
1029 * tool. This integer encodes the package, type, and resource
1030 * entry. The value 0 is an invalid identifier.
1031 *
1032 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1033 *
1034 * @return Returns the boolean value contained in the resource.
1035 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001036 public boolean getBoolean(@BoolRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001037 final TypedValue value = obtainTempTypedValue(id);
1038 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette4d07bc92015-11-16 10:19:12 -05001040 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 return value.data != 0;
1042 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001043 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1044 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1045 } finally {
1046 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048 }
1049
1050 /**
1051 * Return an integer associated with a particular resource ID.
1052 *
1053 * @param id The desired resource identifier, as generated by the aapt
1054 * tool. This integer encodes the package, type, and resource
1055 * entry. The value 0 is an invalid identifier.
1056 *
1057 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1058 *
1059 * @return Returns the integer value contained in the resource.
1060 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001061 public int getInteger(@IntegerRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001062 final TypedValue value = obtainTempTypedValue(id);
1063 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 if (value.type >= TypedValue.TYPE_FIRST_INT
Alan Viverette4d07bc92015-11-16 10:19:12 -05001065 && value.type <= TypedValue.TYPE_LAST_INT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return value.data;
1067 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001068 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1069 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1070 } finally {
1071 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073 }
1074
1075 /**
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001076 * Retrieve a floating-point value for a particular resource ID.
1077 *
1078 * @param id The desired resource identifier, as generated by the aapt
1079 * tool. This integer encodes the package, type, and resource
1080 * entry. The value 0 is an invalid identifier.
1081 *
1082 * @return Returns the floating-point value contained in the resource.
1083 *
1084 * @throws NotFoundException Throws NotFoundException if the given ID does
1085 * not exist or is not a floating-point value.
1086 * @hide Pending API council approval.
1087 */
1088 public float getFloat(int id) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001089 final TypedValue value = obtainTempTypedValue(id);
1090 try {
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001091 if (value.type == TypedValue.TYPE_FLOAT) {
1092 return value.getFloat();
1093 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001094 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1095 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1096 } finally {
1097 releaseTempTypedValue(value);
Alan Viveretteb1e1dbf2014-08-07 17:17:43 -07001098 }
1099 }
1100
1101 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 * Return an XmlResourceParser through which you can read a view layout
1103 * description for the given resource ID. This parser has limited
1104 * functionality -- in particular, you can't change its input, and only
1105 * the high-level events are available.
1106 *
1107 * <p>This function is really a simple wrapper for calling
1108 * {@link #getXml} with a layout resource.
1109 *
1110 * @param id The desired resource identifier, as generated by the aapt
1111 * tool. This integer encodes the package, type, and resource
1112 * entry. The value 0 is an invalid identifier.
1113 *
1114 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1115 *
1116 * @return A new parser object through which you can read
1117 * the XML data.
1118 *
1119 * @see #getXml
1120 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001121 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 return loadXmlResourceParser(id, "layout");
1123 }
1124
1125 /**
1126 * Return an XmlResourceParser through which you can read an animation
1127 * description for the given resource ID. This parser has limited
1128 * functionality -- in particular, you can't change its input, and only
1129 * the high-level events are available.
1130 *
1131 * <p>This function is really a simple wrapper for calling
1132 * {@link #getXml} with an animation resource.
1133 *
1134 * @param id The desired resource identifier, as generated by the aapt
1135 * tool. This integer encodes the package, type, and resource
1136 * entry. The value 0 is an invalid identifier.
1137 *
1138 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1139 *
1140 * @return A new parser object through which you can read
1141 * the XML data.
1142 *
1143 * @see #getXml
1144 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001145 public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 return loadXmlResourceParser(id, "anim");
1147 }
1148
1149 /**
1150 * Return an XmlResourceParser through which you can read a generic XML
1151 * resource for the given resource ID.
1152 *
1153 * <p>The XmlPullParser implementation returned here has some limited
1154 * functionality. In particular, you can't change its input, and only
1155 * high-level parsing events are available (since the document was
1156 * pre-parsed for you at build time, which involved merging text and
1157 * stripping comments).
1158 *
1159 * @param id The desired resource identifier, as generated by the aapt
1160 * tool. This integer encodes the package, type, and resource
1161 * entry. The value 0 is an invalid identifier.
1162 *
1163 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1164 *
1165 * @return A new parser object through which you can read
1166 * the XML data.
1167 *
1168 * @see android.util.AttributeSet
1169 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001170 public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 return loadXmlResourceParser(id, "xml");
1172 }
1173
1174 /**
1175 * Open a data stream for reading a raw resource. This can only be used
1176 * with resources whose value is the name of an asset files -- that is, it can be
1177 * used to open drawable, sound, and raw resources; it will fail on string
1178 * and color resources.
1179 *
1180 * @param id The resource identifier to open, as generated by the appt
1181 * tool.
1182 *
1183 * @return InputStream Access to the resource data.
1184 *
1185 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1186 *
1187 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001188 public InputStream openRawResource(@RawRes int id) throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001189 final TypedValue value = obtainTempTypedValue();
1190 try {
1191 return openRawResource(id, value);
1192 } finally {
1193 releaseTempTypedValue(value);
1194 }
1195 }
1196
1197 /**
1198 * Returns a TypedValue populated with data for the specified resource ID
1199 * that's suitable for temporary use. The obtained TypedValue should be
1200 * released using {@link #releaseTempTypedValue(TypedValue)}.
1201 *
1202 * @param id the resource ID for which data should be obtained
1203 * @return a populated typed value suitable for temporary use
1204 */
1205 private TypedValue obtainTempTypedValue(@AnyRes int id) {
1206 final TypedValue value = obtainTempTypedValue();
1207 getValue(id, value, true);
1208 return value;
1209 }
1210
1211 /**
1212 * Returns a TypedValue suitable for temporary use. The obtained TypedValue
1213 * should be released using {@link #releaseTempTypedValue(TypedValue)}.
1214 *
1215 * @return a typed value suitable for temporary use
1216 */
1217 private TypedValue obtainTempTypedValue() {
1218 TypedValue tmpValue = null;
1219 synchronized (mTmpValueLock) {
1220 if (mTmpValue != null) {
1221 tmpValue = mTmpValue;
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001222 mTmpValue = null;
1223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05001225 if (tmpValue == null) {
1226 return new TypedValue();
1227 }
1228 return tmpValue;
1229 }
1230
1231 /**
1232 * Returns a TypedValue to the pool. After calling this method, the
1233 * specified TypedValue should no longer be accessed.
1234 *
1235 * @param value the typed value to return to the pool
1236 */
1237 private void releaseTempTypedValue(TypedValue value) {
1238 synchronized (mTmpValueLock) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001239 if (mTmpValue == null) {
1240 mTmpValue = value;
1241 }
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244
1245 /**
1246 * Open a data stream for reading a raw resource. This can only be used
Andy Stadlerf8a7cea2009-04-10 16:24:47 -07001247 * 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 -08001248 * used to open drawable, sound, and raw resources; it will fail on string
1249 * and color resources.
1250 *
1251 * @param id The resource identifier to open, as generated by the appt tool.
1252 * @param value The TypedValue object to hold the resource information.
1253 *
1254 * @return InputStream Access to the resource data.
1255 *
1256 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001258 public InputStream openRawResource(@RawRes int id, TypedValue value)
1259 throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 getValue(id, value, true);
1261
1262 try {
1263 return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1264 AssetManager.ACCESS_STREAMING);
1265 } catch (Exception e) {
1266 NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1267 " from drawable resource ID #0x" + Integer.toHexString(id));
1268 rnf.initCause(e);
1269 throw rnf;
1270 }
1271 }
1272
1273 /**
1274 * Open a file descriptor for reading a raw resource. This can only be used
1275 * with resources whose value is the name of an asset files -- that is, it can be
1276 * used to open drawable, sound, and raw resources; it will fail on string
1277 * and color resources.
1278 *
1279 * <p>This function only works for resources that are stored in the package
1280 * as uncompressed data, which typically includes things like mp3 files
1281 * and png images.
1282 *
1283 * @param id The resource identifier to open, as generated by the appt
1284 * tool.
1285 *
1286 * @return AssetFileDescriptor A new file descriptor you can use to read
1287 * the resource. This includes the file descriptor itself, as well as the
1288 * offset and length of data where the resource appears in the file. A
1289 * null is returned if the file exists but is compressed.
1290 *
1291 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1292 *
1293 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001294 public AssetFileDescriptor openRawResourceFd(@RawRes int id)
1295 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001296 final TypedValue value = obtainTempTypedValue(id);
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001297 try {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001298 return mAssets.openNonAssetFd(value.assetCookie, value.string.toString());
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001299 } catch (Exception e) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001300 throw new NotFoundException("File " + value.string.toString() + " from drawable "
1301 + "resource ID #0x" + Integer.toHexString(id), e);
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001302 } finally {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001303 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 }
1306
1307 /**
1308 * Return the raw data associated with a particular resource ID.
1309 *
1310 * @param id The desired resource identifier, as generated by the aapt
1311 * tool. This integer encodes the package, type, and resource
1312 * entry. The value 0 is an invalid identifier.
1313 * @param outValue Object in which to place the resource data.
1314 * @param resolveRefs If true, a resource that is a reference to another
1315 * resource will be followed so that you receive the
1316 * actual final resource data. If false, the TypedValue
1317 * will be filled in with the reference itself.
1318 *
1319 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1320 *
1321 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001322 public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001324 boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 if (found) {
1326 return;
1327 }
1328 throw new NotFoundException("Resource ID #0x"
1329 + Integer.toHexString(id));
1330 }
1331
1332 /**
Kenny Root55fc8502010-10-28 14:47:01 -07001333 * Get the raw value associated with a resource with associated density.
1334 *
1335 * @param id resource identifier
1336 * @param density density in DPI
1337 * @param resolveRefs If true, a resource that is a reference to another
1338 * resource will be followed so that you receive the actual final
1339 * resource data. If false, the TypedValue will be filled in with
1340 * the reference itself.
1341 * @throws NotFoundException Throws NotFoundException if the given ID does
1342 * not exist.
1343 * @see #getValue(String, TypedValue, boolean)
Kenny Root55fc8502010-10-28 14:47:01 -07001344 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001345 public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
1346 boolean resolveRefs) throws NotFoundException {
Kenny Root55fc8502010-10-28 14:47:01 -07001347 boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1348 if (found) {
1349 return;
1350 }
1351 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1352 }
1353
1354 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 * Return the raw data associated with a particular resource ID.
1356 * See getIdentifier() for information on how names are mapped to resource
1357 * IDs, and getString(int) for information on how string resources are
1358 * retrieved.
1359 *
1360 * <p>Note: use of this function is discouraged. It is much more
1361 * efficient to retrieve resources by identifier than by name.
1362 *
1363 * @param name The name of the desired resource. This is passed to
1364 * getIdentifier() with a default type of "string".
1365 * @param outValue Object in which to place the resource data.
1366 * @param resolveRefs If true, a resource that is a reference to another
1367 * resource will be followed so that you receive the
1368 * actual final resource data. If false, the TypedValue
1369 * will be filled in with the reference itself.
1370 *
1371 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1372 *
1373 */
1374 public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1375 throws NotFoundException {
1376 int id = getIdentifier(name, "string", null);
1377 if (id != 0) {
1378 getValue(id, outValue, resolveRefs);
1379 return;
1380 }
1381 throw new NotFoundException("String resource name " + name);
1382 }
1383
1384 /**
1385 * This class holds the current attribute values for a particular theme.
1386 * In other words, a Theme is a set of values for resource attributes;
1387 * these are used in conjunction with {@link TypedArray}
1388 * to resolve the final value for an attribute.
1389 *
1390 * <p>The Theme's attributes come into play in two ways: (1) a styled
1391 * attribute can explicit reference a value in the theme through the
1392 * "?themeAttribute" syntax; (2) if no value has been defined for a
1393 * particular styled attribute, as a last resort we will try to find that
1394 * attribute's value in the Theme.
1395 *
1396 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1397 * retrieve XML attributes with style and theme information applied.
1398 */
1399 public final class Theme {
1400 /**
1401 * Place new attribute values into the theme. The style resource
1402 * specified by <var>resid</var> will be retrieved from this Theme's
1403 * resources, its values placed into the Theme object.
1404 *
1405 * <p>The semantics of this function depends on the <var>force</var>
1406 * argument: If false, only values that are not already defined in
1407 * the theme will be copied from the system resource; otherwise, if
1408 * any of the style's attributes are already defined in the theme, the
1409 * current values in the theme will be overwritten.
1410 *
Alan Viverette75257ce2014-05-22 19:31:38 -07001411 * @param resId The resource ID of a style resource from which to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 * obtain attribute values.
1413 * @param force If true, values in the style resource will always be
1414 * used in the theme; otherwise, they will only be used
1415 * if not already defined in the theme.
1416 */
Alan Viverette75257ce2014-05-22 19:31:38 -07001417 public void applyStyle(int resId, boolean force) {
Alan Viverette395cd012015-08-11 17:27:04 -04001418 synchronized (mKey) {
1419 AssetManager.applyThemeStyle(mTheme, resId, force);
Alan Viverette52b999f2014-03-24 18:00:26 -07001420
Alan Viverette395cd012015-08-11 17:27:04 -04001421 mThemeResId = resId;
1422 mKey.append(resId, force);
1423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
1426 /**
1427 * Set this theme to hold the same contents as the theme
1428 * <var>other</var>. If both of these themes are from the same
1429 * Resources object, they will be identical after this function
1430 * returns. If they are from different Resources, only the resources
1431 * they have in common will be set in this theme.
1432 *
1433 * @param other The existing Theme to copy from.
1434 */
1435 public void setTo(Theme other) {
Alan Viverette395cd012015-08-11 17:27:04 -04001436 synchronized (mKey) {
1437 synchronized (other.mKey) {
1438 AssetManager.copyTheme(mTheme, other.mTheme);
Alan Viverette52b999f2014-03-24 18:00:26 -07001439
Alan Viverette395cd012015-08-11 17:27:04 -04001440 mThemeResId = other.mThemeResId;
1441 mKey.setTo(other.getKey());
1442 }
1443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445
1446 /**
John Spurlock330dd532012-12-18 12:03:11 -05001447 * Return a TypedArray holding the values defined by
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 * <var>Theme</var> which are listed in <var>attrs</var>.
1449 *
Scott Main183bf112012-08-13 19:12:13 -07001450 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1451 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 *
1453 * @param attrs The desired attributes.
1454 *
1455 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1456 *
1457 * @return Returns a TypedArray holding an array of the attribute values.
1458 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1459 * when done with it.
1460 *
1461 * @see Resources#obtainAttributes
1462 * @see #obtainStyledAttributes(int, int[])
1463 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1464 */
Tor Norbyec91531a2015-04-01 17:41:55 -07001465 public TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001466 synchronized (mKey) {
1467 final int len = attrs.length;
1468 final TypedArray array = TypedArray.obtain(Resources.this, len);
1469 array.mTheme = this;
1470 AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
1471 return array;
1472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
1474
1475 /**
John Spurlock330dd532012-12-18 12:03:11 -05001476 * Return a TypedArray holding the values defined by the style
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * resource <var>resid</var> which are listed in <var>attrs</var>.
1478 *
Scott Main183bf112012-08-13 19:12:13 -07001479 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1480 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 *
Alan Viverette395cd012015-08-11 17:27:04 -04001482 * @param resId The desired style resource.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 * @param attrs The desired attributes in the style.
1484 *
1485 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1486 *
1487 * @return Returns a TypedArray holding an array of the attribute values.
1488 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1489 * when done with it.
1490 *
1491 * @see Resources#obtainAttributes
1492 * @see #obtainStyledAttributes(int[])
1493 * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1494 */
Alan Viverette395cd012015-08-11 17:27:04 -04001495 public TypedArray obtainStyledAttributes(@StyleRes int resId, @StyleableRes int[] attrs)
Tor Norbyec91531a2015-04-01 17:41:55 -07001496 throws NotFoundException {
Alan Viverette395cd012015-08-11 17:27:04 -04001497 synchronized (mKey) {
1498 final int len = attrs.length;
1499 final TypedArray array = TypedArray.obtain(Resources.this, len);
1500 array.mTheme = this;
1501 AssetManager.applyStyle(mTheme, 0, resId, 0, attrs, array.mData, array.mIndices);
1502 return array;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505
1506 /**
John Spurlock330dd532012-12-18 12:03:11 -05001507 * Return a TypedArray holding the attribute values in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 * <var>set</var>
1509 * that are listed in <var>attrs</var>. In addition, if the given
1510 * AttributeSet specifies a style class (through the "style" attribute),
1511 * that style will be applied on top of the base attributes it defines.
1512 *
Scott Main183bf112012-08-13 19:12:13 -07001513 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1514 * with the array.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 *
1516 * <p>When determining the final value of a particular attribute, there
1517 * are four inputs that come into play:</p>
1518 *
1519 * <ol>
1520 * <li> Any attribute values in the given AttributeSet.
1521 * <li> The style resource specified in the AttributeSet (named
1522 * "style").
1523 * <li> The default style specified by <var>defStyleAttr</var> and
1524 * <var>defStyleRes</var>
1525 * <li> The base values in this theme.
1526 * </ol>
1527 *
1528 * <p>Each of these inputs is considered in-order, with the first listed
1529 * taking precedence over the following ones. In other words, if in the
1530 * AttributeSet you have supplied <code>&lt;Button
1531 * textColor="#ff000000"&gt;</code>, then the button's text will
1532 * <em>always</em> be black, regardless of what is specified in any of
1533 * the styles.
1534 *
1535 * @param set The base set of attribute values. May be null.
1536 * @param attrs The desired attributes to be retrieved.
1537 * @param defStyleAttr An attribute in the current theme that contains a
1538 * reference to a style resource that supplies
John Spurlock330dd532012-12-18 12:03:11 -05001539 * defaults values for the TypedArray. Can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 * 0 to not look for defaults.
1541 * @param defStyleRes A resource identifier of a style resource that
John Spurlock330dd532012-12-18 12:03:11 -05001542 * supplies default values for the TypedArray,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 * used only if defStyleAttr is 0 or can not be found
1544 * in the theme. Can be 0 to not look for defaults.
1545 *
1546 * @return Returns a TypedArray holding an array of the attribute values.
1547 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1548 * when done with it.
1549 *
1550 * @see Resources#obtainAttributes
1551 * @see #obtainStyledAttributes(int[])
1552 * @see #obtainStyledAttributes(int, int[])
1553 */
1554 public TypedArray obtainStyledAttributes(AttributeSet set,
Tor Norbyec91531a2015-04-01 17:41:55 -07001555 @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
Alan Viverette395cd012015-08-11 17:27:04 -04001556 synchronized (mKey) {
1557 final int len = attrs.length;
1558 final TypedArray array = TypedArray.obtain(Resources.this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
Alan Viverette395cd012015-08-11 17:27:04 -04001560 // XXX note that for now we only work with compiled XML files.
1561 // To support generic XML files we will need to manually parse
1562 // out the attributes from the XML file (applying type information
1563 // contained in the resources and such).
1564 final XmlBlock.Parser parser = (XmlBlock.Parser) set;
1565 AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1566 parser != null ? parser.mParseState : 0,
1567 attrs, array.mData, array.mIndices);
1568 array.mTheme = this;
1569 array.mXml = parser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570
Alan Viverette395cd012015-08-11 17:27:04 -04001571 return array;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
1575 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001576 * Retrieve the values for a set of attributes in the Theme. The
1577 * contents of the typed array are ultimately filled in by
1578 * {@link Resources#getValue}.
1579 *
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001580 * @param values The base set of attribute values, must be equal in
1581 * length to {@code attrs}. All values must be of type
1582 * {@link TypedValue#TYPE_ATTRIBUTE}.
Alan Viverette52b999f2014-03-24 18:00:26 -07001583 * @param attrs The desired attributes to be retrieved.
Alan Viverette52b999f2014-03-24 18:00:26 -07001584 * @return Returns a TypedArray holding an array of the attribute
1585 * values. Be sure to call {@link TypedArray#recycle()}
1586 * when done with it.
1587 * @hide
1588 */
Alan Viverette7f4a63d2014-10-30 10:29:03 -07001589 @NonNull
1590 public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001591 synchronized (mKey) {
1592 final int len = attrs.length;
1593 if (values == null || len != values.length) {
1594 throw new IllegalArgumentException(
1595 "Base attribute values must the same length as attrs");
1596 }
1597
1598 final TypedArray array = TypedArray.obtain(Resources.this, len);
1599 AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
1600 array.mTheme = this;
1601 array.mXml = null;
1602
1603 return array;
Alan Viverette52b999f2014-03-24 18:00:26 -07001604 }
Alan Viverette52b999f2014-03-24 18:00:26 -07001605 }
1606
1607 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 * Retrieve the value of an attribute in the Theme. The contents of
1609 * <var>outValue</var> are ultimately filled in by
1610 * {@link Resources#getValue}.
1611 *
1612 * @param resid The resource identifier of the desired theme
1613 * attribute.
1614 * @param outValue Filled in with the ultimate resource value supplied
1615 * by the attribute.
1616 * @param resolveRefs If true, resource references will be walked; if
1617 * false, <var>outValue</var> may be a
1618 * TYPE_REFERENCE. In either case, it will never
1619 * be a TYPE_ATTRIBUTE.
1620 *
1621 * @return boolean Returns true if the attribute was found and
1622 * <var>outValue</var> is valid, else false.
1623 */
Alan Viverette52b999f2014-03-24 18:00:26 -07001624 public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
Alan Viverette395cd012015-08-11 17:27:04 -04001625 synchronized (mKey) {
1626 return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629
1630 /**
Jon Miranda042ad632014-09-03 17:57:35 -07001631 * Gets all of the attribute ids associated with this {@link Theme}. For debugging only.
1632 *
1633 * @return The int array containing attribute ids associated with this {@link Theme}.
1634 * @hide
1635 */
1636 public int[] getAllAttributes() {
1637 return mAssets.getStyleAttributes(getAppliedStyleResId());
1638 }
1639
1640 /**
Alan Viverette52b999f2014-03-24 18:00:26 -07001641 * Returns the resources to which this theme belongs.
1642 *
1643 * @return Resources to which this theme belongs.
1644 */
1645 public Resources getResources() {
1646 return Resources.this;
1647 }
1648
1649 /**
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001650 * Return a drawable object associated with a particular resource ID
1651 * and styled for the Theme.
1652 *
1653 * @param id The desired resource identifier, as generated by the aapt
1654 * tool. This integer encodes the package, type, and resource
1655 * entry. The value 0 is an invalid identifier.
1656 * @return Drawable An object that can be used to draw this resource.
1657 * @throws NotFoundException Throws NotFoundException if the given ID
1658 * does not exist.
1659 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07001660 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001661 return Resources.this.getDrawable(id, this);
1662 }
1663
1664 /**
Alan Viverettec1d52792015-05-05 09:49:03 -07001665 * Returns a bit mask of configuration changes that will impact this
1666 * theme (and thus require completely reloading it).
1667 *
1668 * @return a bit mask of configuration changes, as defined by
1669 * {@link ActivityInfo}
1670 * @see ActivityInfo
1671 */
1672 public int getChangingConfigurations() {
Alan Viverette395cd012015-08-11 17:27:04 -04001673 synchronized (mKey) {
1674 final int nativeChangingConfig =
1675 AssetManager.getThemeChangingConfigurations(mTheme);
1676 return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
1677 }
Alan Viverettec1d52792015-05-05 09:49:03 -07001678 }
1679
1680 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 * Print contents of this theme out to the log. For debugging only.
1682 *
1683 * @param priority The log priority to use.
1684 * @param tag The log tag to use.
1685 * @param prefix Text to prefix each line printed.
1686 */
1687 public void dump(int priority, String tag, String prefix) {
Alan Viverette395cd012015-08-11 17:27:04 -04001688 synchronized (mKey) {
1689 AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001692
1693 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 protected void finalize() throws Throwable {
1695 super.finalize();
1696 mAssets.releaseTheme(mTheme);
1697 }
1698
1699 /*package*/ Theme() {
1700 mAssets = Resources.this.mAssets;
1701 mTheme = mAssets.createTheme();
1702 }
1703
Alan Viverettee54d2452015-05-06 10:41:43 -07001704 /** Unique key for the series of styles applied to this theme. */
1705 private final ThemeKey mKey = new ThemeKey();
1706
Alan Viverette8eea3ea2014-02-03 18:40:20 -08001707 @SuppressWarnings("hiding")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 private final AssetManager mAssets;
Ashok Bhat896043d2014-01-17 16:02:38 +00001709 private final long mTheme;
Alan Viverette52b999f2014-03-24 18:00:26 -07001710
Alan Viverette351f0c12014-03-28 15:25:27 -07001711 /** Resource identifier for the theme. */
Alan Viverette52b999f2014-03-24 18:00:26 -07001712 private int mThemeResId = 0;
Deepanshu Guptabfec73c2014-03-11 18:02:44 -07001713
1714 // Needed by layoutlib.
1715 /*package*/ long getNativeTheme() {
1716 return mTheme;
1717 }
1718
1719 /*package*/ int getAppliedStyleResId() {
1720 return mThemeResId;
1721 }
Alan Viverette75257ce2014-05-22 19:31:38 -07001722
Alan Viverettee54d2452015-05-06 10:41:43 -07001723 /*package*/ ThemeKey getKey() {
Alan Viverette75257ce2014-05-22 19:31:38 -07001724 return mKey;
1725 }
Jon Miranda836c0a82014-08-11 12:32:26 -07001726
1727 private String getResourceNameFromHexString(String hexString) {
1728 return getResourceName(Integer.parseInt(hexString, 16));
1729 }
1730
1731 /**
Alan Viverettee54d2452015-05-06 10:41:43 -07001732 * Parses {@link #mKey} and returns a String array that holds pairs of
1733 * adjacent Theme data: resource name followed by whether or not it was
1734 * forced, as specified by {@link #applyStyle(int, boolean)}.
Jon Miranda836c0a82014-08-11 12:32:26 -07001735 *
1736 * @hide
1737 */
1738 @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
1739 public String[] getTheme() {
Alan Viverette395cd012015-08-11 17:27:04 -04001740 synchronized (mKey) {
1741 final int N = mKey.mCount;
1742 final String[] themes = new String[N * 2];
1743 for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
1744 final int resId = mKey.mResId[j];
1745 final boolean forced = mKey.mForce[j];
1746 try {
1747 themes[i] = getResourceName(resId);
1748 } catch (NotFoundException e) {
1749 themes[i] = Integer.toHexString(i);
1750 }
1751 themes[i + 1] = forced ? "forced" : "not forced";
Siva Velusamy0d857b92015-04-22 10:23:56 -07001752 }
Alan Viverette395cd012015-08-11 17:27:04 -04001753 return themes;
Jon Miranda836c0a82014-08-11 12:32:26 -07001754 }
Jon Miranda836c0a82014-08-11 12:32:26 -07001755 }
Alan Viverettee54d2452015-05-06 10:41:43 -07001756
Siva Velusamy0d857b92015-04-22 10:23:56 -07001757 /** @hide */
1758 public void encode(@NonNull ViewHierarchyEncoder encoder) {
1759 encoder.beginObject(this);
Alan Viveretteac674092015-05-08 11:04:47 -07001760 final String[] properties = getTheme();
Siva Velusamy0d857b92015-04-22 10:23:56 -07001761 for (int i = 0; i < properties.length; i += 2) {
1762 encoder.addProperty(properties[i], properties[i+1]);
1763 }
1764 encoder.endObject();
1765 }
1766
Alan Viverettee54d2452015-05-06 10:41:43 -07001767 /**
1768 * Rebases the theme against the parent Resource object's current
1769 * configuration by re-applying the styles passed to
1770 * {@link #applyStyle(int, boolean)}.
1771 *
1772 * @hide
1773 */
1774 public void rebase() {
Alan Viverette395cd012015-08-11 17:27:04 -04001775 synchronized (mKey) {
1776 AssetManager.clearTheme(mTheme);
Alan Viverettee54d2452015-05-06 10:41:43 -07001777
Alan Viverette395cd012015-08-11 17:27:04 -04001778 // Reapply the same styles in the same order.
1779 for (int i = 0; i < mKey.mCount; i++) {
1780 final int resId = mKey.mResId[i];
1781 final boolean force = mKey.mForce[i];
1782 AssetManager.applyThemeStyle(mTheme, resId, force);
1783 }
Alan Viverettee54d2452015-05-06 10:41:43 -07001784 }
1785 }
1786 }
1787
1788 static class ThemeKey implements Cloneable {
1789 int[] mResId;
1790 boolean[] mForce;
1791 int mCount;
1792
1793 private int mHashCode = 0;
1794
1795 public void append(int resId, boolean force) {
1796 if (mResId == null) {
1797 mResId = new int[4];
1798 }
1799
1800 if (mForce == null) {
1801 mForce = new boolean[4];
1802 }
1803
1804 mResId = GrowingArrayUtils.append(mResId, mCount, resId);
1805 mForce = GrowingArrayUtils.append(mForce, mCount, force);
1806 mCount++;
1807
1808 mHashCode = 31 * (31 * mHashCode + resId) + (force ? 1 : 0);
1809 }
1810
1811 /**
1812 * Sets up this key as a deep copy of another key.
1813 *
1814 * @param other the key to deep copy into this key
1815 */
1816 public void setTo(ThemeKey other) {
1817 mResId = other.mResId == null ? null : other.mResId.clone();
1818 mForce = other.mForce == null ? null : other.mForce.clone();
1819 mCount = other.mCount;
1820 }
1821
1822 @Override
1823 public int hashCode() {
1824 return mHashCode;
1825 }
1826
1827 @Override
1828 public boolean equals(Object o) {
1829 if (this == o) {
1830 return true;
1831 }
1832
1833 if (o == null || getClass() != o.getClass() || hashCode() != o.hashCode()) {
1834 return false;
1835 }
1836
1837 final ThemeKey t = (ThemeKey) o;
1838 if (mCount != t.mCount) {
1839 return false;
1840 }
1841
1842 final int N = mCount;
1843 for (int i = 0; i < N; i++) {
1844 if (mResId[i] != t.mResId[i] || mForce[i] != t.mForce[i]) {
1845 return false;
1846 }
1847 }
1848
1849 return true;
1850 }
1851
1852 /**
1853 * @return a shallow copy of this key
1854 */
1855 @Override
1856 public ThemeKey clone() {
1857 final ThemeKey other = new ThemeKey();
1858 other.mResId = mResId;
1859 other.mForce = mForce;
1860 other.mCount = mCount;
John Reck4feb3262015-07-13 14:42:43 -07001861 other.mHashCode = mHashCode;
Alan Viverettee54d2452015-05-06 10:41:43 -07001862 return other;
1863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
1865
1866 /**
1867 * Generate a new Theme object for this set of Resources. It initially
1868 * starts out empty.
Jon Miranda836c0a82014-08-11 12:32:26 -07001869 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 * @return Theme The newly created Theme container.
1871 */
1872 public final Theme newTheme() {
1873 return new Theme();
1874 }
1875
1876 /**
1877 * Retrieve a set of basic attribute values from an AttributeSet, not
1878 * performing styling of them using a theme and/or style resources.
Jon Miranda836c0a82014-08-11 12:32:26 -07001879 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 * @param set The current attribute values to retrieve.
1881 * @param attrs The specific attributes to be retrieved.
1882 * @return Returns a TypedArray holding an array of the attribute values.
1883 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1884 * when done with it.
1885 *
1886 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1887 */
1888 public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1889 int len = attrs.length;
Alan Viverette52b999f2014-03-24 18:00:26 -07001890 TypedArray array = TypedArray.obtain(this, len);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891
1892 // XXX note that for now we only work with compiled XML files.
1893 // To support generic XML files we will need to manually parse
1894 // out the attributes from the XML file (applying type information
1895 // contained in the resources and such).
1896 XmlBlock.Parser parser = (XmlBlock.Parser)set;
1897 mAssets.retrieveAttributes(parser.mParseState, attrs,
1898 array.mData, array.mIndices);
1899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 array.mXml = parser;
1901
1902 return array;
1903 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 /**
1906 * Store the newly updated configuration.
1907 */
1908 public void updateConfiguration(Configuration config,
1909 DisplayMetrics metrics) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001910 updateConfiguration(config, metrics, null);
1911 }
1912
1913 /**
1914 * @hide
1915 */
1916 public void updateConfiguration(Configuration config,
1917 DisplayMetrics metrics, CompatibilityInfo compat) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001918 synchronized (mAccessLock) {
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001919 if (false) {
1920 Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1921 + mConfiguration + " old compat is " + mCompatibilityInfo);
1922 Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1923 + config + " new compat is " + compat);
1924 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001925 if (compat != null) {
1926 mCompatibilityInfo = compat;
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 if (metrics != null) {
1929 mMetrics.setTo(metrics);
1930 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001931 // NOTE: We should re-arrange this code to create a Display
1932 // with the CompatibilityInfo that is used everywhere we deal
1933 // with the display in relation to this app, rather than
1934 // doing the conversion here. This impl should be okay because
1935 // we make sure to return a compatible display in the places
1936 // where there are public APIs to retrieve the display... but
1937 // it would be cleaner and more maintainble to just be
1938 // consistently dealing with a compatible display everywhere in
1939 // the framework.
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07001940 mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1941
Alan Viverettea8636c92015-03-27 10:44:39 -07001942 final int configChanges = calcConfigChanges(config);
Roozbeh Pournaderdad10062015-12-14 16:15:52 -08001943
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001944 LocaleList locales = mConfiguration.getLocales();
Raph Levien1f0945e2016-01-20 12:16:50 -08001945 if (locales.isEmpty()) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -08001946 locales = LocaleList.getAdjustedDefault();
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001947 mConfiguration.setLocales(locales);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001948 }
Dianne Hackborn756220b2012-08-14 16:45:30 -07001949 if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1950 mMetrics.densityDpi = mConfiguration.densityDpi;
1951 mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1952 }
Dianne Hackborn2b31d532011-06-23 11:58:50 -07001953 mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001954
Alan Viverettea8636c92015-03-27 10:44:39 -07001955 final int width, height;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1957 width = mMetrics.widthPixels;
1958 height = mMetrics.heightPixels;
1959 } else {
1960 //noinspection SuspiciousNameCombination
1961 width = mMetrics.heightPixels;
1962 //noinspection SuspiciousNameCombination
1963 height = mMetrics.widthPixels;
1964 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001965
1966 final int keyboardHidden;
1967 if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1968 && mConfiguration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
Alan Viverettea8636c92015-03-27 10:44:39 -07001970 } else {
1971 keyboardHidden = mConfiguration.keyboardHidden;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 }
Alan Viverettea8636c92015-03-27 10:44:39 -07001973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
Roozbeh Pournaderfee44842016-02-04 15:24:24 -08001975 adjustLanguageTag(locales.get(0).toLanguageTag()),
Roozbeh Pournader47571c72015-09-01 14:07:04 -07001976 mConfiguration.orientation,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 mConfiguration.touchscreen,
Dianne Hackborn908aecc2012-07-31 16:37:34 -07001978 mConfiguration.densityDpi, mConfiguration.keyboard,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 keyboardHidden, mConfiguration.navigation, width, height,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07001980 mConfiguration.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07001981 mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
Dianne Hackborn3b81bc12011-01-15 11:50:52 -08001982 mConfiguration.screenLayout, mConfiguration.uiMode,
1983 Build.VERSION.RESOURCES_SDK_INT);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001984
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001985 if (DEBUG_CONFIG) {
Alan Viverette4d07bc92015-11-16 10:19:12 -05001986 Slog.i(TAG, "**** Updating config of " + this + ": final config is "
1987 + mConfiguration + " final compat is " + mCompatibilityInfo);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001988 }
1989
Alan Viverettee54d2452015-05-06 10:41:43 -07001990 mDrawableCache.onConfigurationChange(configChanges);
1991 mColorDrawableCache.onConfigurationChange(configChanges);
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08001992 mComplexColorCache.onConfigurationChange(configChanges);
Yigit Boyard422dc32014-09-25 12:23:35 -07001993 mAnimatorCache.onConfigurationChange(configChanges);
1994 mStateListAnimatorCache.onConfigurationChange(configChanges);
Masanori Oginoc7d9d272010-07-10 12:10:41 +09001995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 flushLayoutCache();
1997 }
Dianne Hackborn50707cc2013-02-08 15:32:05 -08001998 synchronized (sSync) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 if (mPluralRule != null) {
Roozbeh Pournaderfee44842016-02-04 15:24:24 -08002000 mPluralRule = PluralRules.forLocale(mConfiguration.getLocales().get(0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002 }
2003 }
2004
Yigit Boyard422dc32014-09-25 12:23:35 -07002005 /**
2006 * Called by ConfigurationBoundResourceCacheTest via reflection.
2007 */
2008 private int calcConfigChanges(Configuration config) {
2009 int configChanges = 0xfffffff;
2010 if (config != null) {
2011 mTmpConfig.setTo(config);
2012 int density = config.densityDpi;
2013 if (density == Configuration.DENSITY_DPI_UNDEFINED) {
2014 density = mMetrics.noncompatDensityDpi;
2015 }
2016
2017 mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
2018
Roozbeh Pournader47571c72015-09-01 14:07:04 -07002019 if (mTmpConfig.getLocales().isEmpty()) {
2020 mTmpConfig.setLocales(LocaleList.getDefault());
Yigit Boyard422dc32014-09-25 12:23:35 -07002021 }
2022 configChanges = mConfiguration.updateFrom(mTmpConfig);
2023 configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
2024 }
2025 return configChanges;
2026 }
2027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 /**
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002029 * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
2030 * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
2031 *
2032 * All released versions of android prior to "L" used the deprecated language
2033 * tags, so we will need to support them for backwards compatibility.
2034 *
2035 * Note that this conversion needs to take place *after* the call to
2036 * {@code toLanguageTag} because that will convert all the deprecated codes to
2037 * the new ones, even if they're set manually.
2038 */
2039 private static String adjustLanguageTag(String languageTag) {
2040 final int separator = languageTag.indexOf('-');
2041 final String language;
2042 final String remainder;
2043
2044 if (separator == -1) {
2045 language = languageTag;
2046 remainder = "";
2047 } else {
2048 language = languageTag.substring(0, separator);
2049 remainder = languageTag.substring(separator);
2050 }
2051
Narayan Kamath4c6ce232014-07-18 16:09:36 +01002052 return Locale.adjustLanguageCode(language) + remainder;
Narayan Kamath21fc8ba2014-03-05 18:42:23 +00002053 }
2054
2055 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 * Update the system resources configuration if they have previously
2057 * been initialized.
2058 *
2059 * @hide
2060 */
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002061 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
2062 CompatibilityInfo compat) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 if (mSystem != null) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002064 mSystem.updateConfiguration(config, metrics, compat);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 //Log.i(TAG, "Updated system resources " + mSystem
2066 // + ": " + mSystem.getConfiguration());
2067 }
2068 }
2069
2070 /**
2071 * Return the current display metrics that are in effect for this resource
2072 * object. The returned object should be treated as read-only.
2073 *
2074 * @return The resource's current display metrics.
2075 */
2076 public DisplayMetrics getDisplayMetrics() {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07002077 if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
2078 + "x" + mMetrics.heightPixels + " " + mMetrics.density);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 return mMetrics;
2080 }
2081
2082 /**
2083 * Return the current configuration that is in effect for this resource
2084 * object. The returned object should be treated as read-only.
2085 *
2086 * @return The resource's current configuration.
2087 */
2088 public Configuration getConfiguration() {
2089 return mConfiguration;
2090 }
Filip Gruszczynski23493322015-07-29 17:02:59 -07002091
2092 /** @hide */
2093 public Configuration[] getSizeConfigurations() {
2094 return mAssets.getSizeConfigurations();
2095 };
2096
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002097 /**
2098 * Return the compatibility mode information for the application.
2099 * The returned object should be treated as read-only.
2100 *
Dianne Hackborn3904d032011-05-27 12:09:11 -07002101 * @return compatibility info.
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002102 * @hide
2103 */
2104 public CompatibilityInfo getCompatibilityInfo() {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002105 return mCompatibilityInfo;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
2108 /**
Dianne Hackborna53b8282009-07-17 11:13:48 -07002109 * This is just for testing.
2110 * @hide
2111 */
2112 public void setCompatibilityInfo(CompatibilityInfo ci) {
Adam Lesinski79a8ffe2013-09-19 20:33:15 -07002113 if (ci != null) {
2114 mCompatibilityInfo = ci;
2115 updateConfiguration(mConfiguration, mMetrics);
2116 }
Dianne Hackborna53b8282009-07-17 11:13:48 -07002117 }
2118
2119 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 * Return a resource identifier for the given resource name. A fully
2121 * qualified resource name is of the form "package:type/entry". The first
2122 * two components (package and type) are optional if defType and
2123 * defPackage, respectively, are specified here.
2124 *
2125 * <p>Note: use of this function is discouraged. It is much more
2126 * efficient to retrieve resources by identifier than by name.
2127 *
2128 * @param name The name of the desired resource.
2129 * @param defType Optional default resource type to find, if "type/" is
2130 * not included in the name. Can be null to require an
2131 * explicit type.
2132 * @param defPackage Optional default package to find, if "package:" is
2133 * not included in the name. Can be null to require an
2134 * explicit package.
2135 *
2136 * @return int The associated resource identifier. Returns 0 if no such
2137 * resource was found. (0 is not a valid resource ID.)
2138 */
2139 public int getIdentifier(String name, String defType, String defPackage) {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002140 if (name == null) {
2141 throw new NullPointerException("name is null");
2142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 try {
2144 return Integer.parseInt(name);
2145 } catch (Exception e) {
2146 // Ignore
2147 }
2148 return mAssets.getResourceIdentifier(name, defType, defPackage);
2149 }
2150
2151 /**
Jeff Sharkey47b50332013-03-15 14:46:46 -07002152 * Return true if given resource identifier includes a package.
2153 *
2154 * @hide
2155 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002156 public static boolean resourceHasPackage(@AnyRes int resid) {
Jeff Sharkey47b50332013-03-15 14:46:46 -07002157 return (resid >>> 24) != 0;
2158 }
2159
2160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 * Return the full name for a given resource identifier. This name is
2162 * a single string of the form "package:type/entry".
2163 *
2164 * @param resid The resource identifier whose name is to be retrieved.
2165 *
2166 * @return A string holding the name of the resource.
2167 *
2168 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2169 *
2170 * @see #getResourcePackageName
2171 * @see #getResourceTypeName
2172 * @see #getResourceEntryName
2173 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002174 public String getResourceName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 String str = mAssets.getResourceName(resid);
2176 if (str != null) return str;
2177 throw new NotFoundException("Unable to find resource ID #0x"
2178 + Integer.toHexString(resid));
2179 }
2180
2181 /**
2182 * Return the package name for a given resource identifier.
2183 *
2184 * @param resid The resource identifier whose package name is to be
2185 * retrieved.
2186 *
2187 * @return A string holding the package name of the resource.
2188 *
2189 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2190 *
2191 * @see #getResourceName
2192 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002193 public String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 String str = mAssets.getResourcePackageName(resid);
2195 if (str != null) return str;
2196 throw new NotFoundException("Unable to find resource ID #0x"
2197 + Integer.toHexString(resid));
2198 }
2199
2200 /**
2201 * Return the type name for a given resource identifier.
2202 *
2203 * @param resid The resource identifier whose type name is to be
2204 * retrieved.
2205 *
2206 * @return A string holding the type name of the resource.
2207 *
2208 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2209 *
2210 * @see #getResourceName
2211 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002212 public String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 String str = mAssets.getResourceTypeName(resid);
2214 if (str != null) return str;
2215 throw new NotFoundException("Unable to find resource ID #0x"
2216 + Integer.toHexString(resid));
2217 }
2218
2219 /**
2220 * Return the entry name for a given resource identifier.
2221 *
2222 * @param resid The resource identifier whose entry name is to be
2223 * retrieved.
2224 *
2225 * @return A string holding the entry name of the resource.
2226 *
2227 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2228 *
2229 * @see #getResourceName
2230 */
Tor Norbye7b9c9122013-05-30 16:48:33 -07002231 public String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 String str = mAssets.getResourceEntryName(resid);
2233 if (str != null) return str;
2234 throw new NotFoundException("Unable to find resource ID #0x"
2235 + Integer.toHexString(resid));
2236 }
2237
2238 /**
2239 * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2240 * an XML file. You call this when you are at the parent tag of the
Dianne Hackborndef15372010-08-15 12:43:52 -07002241 * 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 -08002242 * This will call {@link #parseBundleExtra} for each extra tag encountered.
2243 *
2244 * @param parser The parser from which to retrieve the extras.
2245 * @param outBundle A Bundle in which to place all parsed extras.
2246 * @throws XmlPullParserException
2247 * @throws IOException
2248 */
2249 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2250 throws XmlPullParserException, IOException {
2251 int outerDepth = parser.getDepth();
2252 int type;
2253 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2254 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2255 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2256 continue;
2257 }
2258
2259 String nodeName = parser.getName();
2260 if (nodeName.equals("extra")) {
2261 parseBundleExtra("extra", parser, outBundle);
2262 XmlUtils.skipCurrentTag(parser);
2263
2264 } else {
2265 XmlUtils.skipCurrentTag(parser);
2266 }
2267 }
2268 }
2269
2270 /**
2271 * Parse a name/value pair out of an XML tag holding that data. The
2272 * AttributeSet must be holding the data defined by
2273 * {@link android.R.styleable#Extra}. The following value types are supported:
2274 * <ul>
2275 * <li> {@link TypedValue#TYPE_STRING}:
2276 * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2277 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2278 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2279 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2280 * {@link Bundle#putCharSequence Bundle.putBoolean()}
2281 * <li> {@link TypedValue#TYPE_FLOAT}:
2282 * {@link Bundle#putCharSequence Bundle.putFloat()}
2283 * </ul>
2284 *
2285 * @param tagName The name of the tag these attributes come from; this is
2286 * only used for reporting error messages.
2287 * @param attrs The attributes from which to retrieve the name/value pair.
2288 * @param outBundle The Bundle in which to place the parsed value.
2289 * @throws XmlPullParserException If the attributes are not valid.
2290 */
2291 public void parseBundleExtra(String tagName, AttributeSet attrs,
2292 Bundle outBundle) throws XmlPullParserException {
2293 TypedArray sa = obtainAttributes(attrs,
2294 com.android.internal.R.styleable.Extra);
2295
2296 String name = sa.getString(
2297 com.android.internal.R.styleable.Extra_name);
2298 if (name == null) {
2299 sa.recycle();
2300 throw new XmlPullParserException("<" + tagName
2301 + "> requires an android:name attribute at "
2302 + attrs.getPositionDescription());
2303 }
2304
2305 TypedValue v = sa.peekValue(
2306 com.android.internal.R.styleable.Extra_value);
2307 if (v != null) {
2308 if (v.type == TypedValue.TYPE_STRING) {
2309 CharSequence cs = v.coerceToString();
2310 outBundle.putCharSequence(name, cs);
2311 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2312 outBundle.putBoolean(name, v.data != 0);
2313 } else if (v.type >= TypedValue.TYPE_FIRST_INT
2314 && v.type <= TypedValue.TYPE_LAST_INT) {
2315 outBundle.putInt(name, v.data);
2316 } else if (v.type == TypedValue.TYPE_FLOAT) {
2317 outBundle.putFloat(name, v.getFloat());
2318 } else {
2319 sa.recycle();
2320 throw new XmlPullParserException("<" + tagName
2321 + "> only supports string, integer, float, color, and boolean at "
2322 + attrs.getPositionDescription());
2323 }
2324 } else {
2325 sa.recycle();
2326 throw new XmlPullParserException("<" + tagName
2327 + "> requires an android:value or android:resource attribute at "
2328 + attrs.getPositionDescription());
2329 }
2330
2331 sa.recycle();
2332 }
2333
2334 /**
2335 * Retrieve underlying AssetManager storage for these resources.
2336 */
2337 public final AssetManager getAssets() {
2338 return mAssets;
2339 }
2340
2341 /**
2342 * Call this to remove all cached loaded layout resources from the
2343 * Resources object. Only intended for use with performance testing
2344 * tools.
2345 */
2346 public final void flushLayoutCache() {
Alan Viverette5c64b952016-02-28 15:16:05 -05002347 synchronized (mCachedXmlBlocks) {
2348 Arrays.fill(mCachedXmlBlockCookies, 0);
2349 Arrays.fill(mCachedXmlBlockFiles, null);
2350
2351 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
2352 for (int i = 0; i < XML_BLOCK_CACHE_SIZE; i++) {
Alan Viverette10979612016-01-06 15:27:35 -05002353 final XmlBlock oldBlock = cachedXmlBlocks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 if (oldBlock != null) {
2355 oldBlock.close();
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
Alan Viverette5c64b952016-02-28 15:16:05 -05002358 Arrays.fill(cachedXmlBlocks, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 }
2360 }
2361
2362 /**
2363 * Start preloading of resource data using this Resources object. Only
2364 * for use by the zygote process for loading common system resources.
2365 * {@hide}
2366 */
2367 public final void startPreloading() {
Dianne Hackborn50707cc2013-02-08 15:32:05 -08002368 synchronized (sSync) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002369 if (sPreloaded) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 throw new IllegalStateException("Resources already preloaded");
2371 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002372 sPreloaded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 mPreloading = true;
Alan Viverette4d07bc92015-11-16 10:19:12 -05002374 mConfiguration.densityDpi = DisplayMetrics.DENSITY_DEVICE;
Dianne Hackborndde331c2012-08-03 14:01:57 -07002375 updateConfiguration(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
2377 }
2378
2379 /**
2380 * Called by zygote when it is done preloading resources, to change back
2381 * to normal Resources operation.
2382 */
2383 public final void finishPreloading() {
2384 if (mPreloading) {
2385 mPreloading = false;
2386 flushLayoutCache();
2387 }
2388 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002389
Romain Guy3b748a42013-04-17 18:54:38 -07002390 /**
2391 * @hide
2392 */
Alan Viverette52b999f2014-03-24 18:00:26 -07002393 public LongSparseArray<ConstantState> getPreloadedDrawables() {
Romain Guy3b748a42013-04-17 18:54:38 -07002394 return sPreloadedDrawables[0];
2395 }
2396
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002397 private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2398 int resourceId, String name) {
2399 // We allow preloading of resources even if they vary by font scale (which
2400 // doesn't impact resource selection) or density (which we handle specially by
2401 // simply turning off all preloading), as well as any other configs specified
2402 // by the caller.
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002403 if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
Dianne Hackbornf1ae2692013-04-19 14:09:37 -07002404 ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
Dianne Hackborndde331c2012-08-03 14:01:57 -07002405 String resName;
2406 try {
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002407 resName = getResourceName(resourceId);
Dianne Hackborndde331c2012-08-03 14:01:57 -07002408 } catch (NotFoundException e) {
2409 resName = "?";
2410 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002411 // This should never happen in production, so we should log a
2412 // warning even if we're not debugging.
Dianne Hackborndde331c2012-08-03 14:01:57 -07002413 Log.w(TAG, "Preloaded " + name + " resource #0x"
Fabrice Di Megliodc25d252013-04-09 18:04:29 -07002414 + Integer.toHexString(resourceId)
Dianne Hackborndde331c2012-08-03 14:01:57 -07002415 + " (" + resName + ") that varies with configuration!!");
2416 return false;
2417 }
Fabrice Di Megliob9a13b82013-04-15 14:05:30 -07002418 if (TRACE_FOR_PRELOAD) {
2419 String resName;
2420 try {
2421 resName = getResourceName(resourceId);
2422 } catch (NotFoundException e) {
2423 resName = "?";
2424 }
2425 Log.w(TAG, "Preloading " + name + " resource #0x"
2426 + Integer.toHexString(resourceId)
2427 + " (" + resName + ")");
2428 }
Dianne Hackborndde331c2012-08-03 14:01:57 -07002429 return true;
2430 }
2431
Alan Viverette0f1c95e2015-06-05 10:17:21 -07002432 @Nullable
2433 Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
Alan Viverette7941a7f2016-01-06 11:11:53 -05002434 return loadDrawable(value, id, theme, true);
2435 }
2436
2437 @Nullable
2438 Drawable loadDrawable(TypedValue value, int id, Theme theme, boolean useCache)
2439 throws NotFoundException {
Alan Viverettec078c602015-12-08 14:49:13 -05002440 try {
2441 if (TRACE_FOR_PRELOAD) {
2442 // Log only framework resources
2443 if ((id >>> 24) == 0x1) {
2444 final String name = getResourceName(id);
2445 if (name != null) {
2446 Log.d("PreloadDrawable", name);
2447 }
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450
Alan Viverettec078c602015-12-08 14:49:13 -05002451 final boolean isColorDrawable;
2452 final DrawableCache caches;
2453 final long key;
2454 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2455 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2456 isColorDrawable = true;
2457 caches = mColorDrawableCache;
2458 key = value.data;
2459 } else {
2460 isColorDrawable = false;
2461 caches = mDrawableCache;
2462 key = (((long) value.assetCookie) << 32) | value.data;
Alan Viverette52b999f2014-03-24 18:00:26 -07002463 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002464
Alan Viverettec078c602015-12-08 14:49:13 -05002465 // First, check whether we have a cached version of this drawable
Alan Viverette7941a7f2016-01-06 11:11:53 -05002466 // that was inflated against the specified theme. Skip the cache if
2467 // we're currently preloading or we're not using the cache.
2468 if (!mPreloading && useCache) {
Alan Viverettec078c602015-12-08 14:49:13 -05002469 final Drawable cachedDrawable = caches.getInstance(key, theme);
2470 if (cachedDrawable != null) {
2471 return cachedDrawable;
2472 }
2473 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002474
Alan Viverette7941a7f2016-01-06 11:11:53 -05002475 // Next, check preloaded drawables. Preloaded drawables may contain
2476 // unresolved theme attributes.
Alan Viverettec078c602015-12-08 14:49:13 -05002477 final ConstantState cs;
2478 if (isColorDrawable) {
2479 cs = sPreloadedColorDrawables.get(key);
2480 } else {
2481 cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2482 }
Alan Viverette4325f8e2015-04-01 15:00:30 -07002483
Alan Viverettec078c602015-12-08 14:49:13 -05002484 Drawable dr;
2485 if (cs != null) {
2486 dr = cs.newDrawable(this);
2487 } else if (isColorDrawable) {
2488 dr = new ColorDrawable(value.data);
2489 } else {
2490 dr = loadDrawableForCookie(value, id, null);
2491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492
Alan Viverettec078c602015-12-08 14:49:13 -05002493 // Determine if the drawable has unresolved theme attributes. If it
2494 // does, we'll need to apply a theme and store it in a theme-specific
2495 // cache.
2496 final boolean canApplyTheme = dr != null && dr.canApplyTheme();
2497 if (canApplyTheme && theme != null) {
2498 dr = dr.mutate();
2499 dr.applyTheme(theme);
2500 dr.clearMutated();
2501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502
Alan Viverettec078c602015-12-08 14:49:13 -05002503 // If we were able to obtain a drawable, store it in the appropriate
Alan Viverette7941a7f2016-01-06 11:11:53 -05002504 // cache: preload, not themed, null theme, or theme-specific. Don't
2505 // pollute the cache with drawables loaded from a foreign density.
2506 if (dr != null && useCache) {
Alan Viverettec078c602015-12-08 14:49:13 -05002507 dr.setChangingConfigurations(value.changingConfigurations);
2508 cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
2509 }
2510
2511 return dr;
2512 } catch (Exception e) {
2513 String name;
2514 try {
2515 name = getResourceName(id);
2516 } catch (NotFoundException e2) {
2517 name = "(missing name)";
2518 }
2519
2520 // The target drawable might fail to load for any number of
2521 // reasons, but we always want to include the resource name.
2522 // Since the client already expects this method to throw a
2523 // NotFoundException, just throw one of those.
2524 final NotFoundException nfe = new NotFoundException("Drawable " + name
2525 + " with resource ID #0x" + Integer.toHexString(id), e);
2526 nfe.setStackTrace(new StackTraceElement[0]);
2527 throw nfe;
2528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
2530
Alan Viverettee54d2452015-05-06 10:41:43 -07002531 private void cacheDrawable(TypedValue value, boolean isColorDrawable, DrawableCache caches,
2532 Theme theme, boolean usesTheme, long key, Drawable dr) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002533 final ConstantState cs = dr.getConstantState();
2534 if (cs == null) {
2535 return;
2536 }
2537
Alan Viverette52b999f2014-03-24 18:00:26 -07002538 if (mPreloading) {
Alan Viverette52b999f2014-03-24 18:00:26 -07002539 final int changingConfigs = cs.getChangingConfigurations();
2540 if (isColorDrawable) {
2541 if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2542 sPreloadedColorDrawables.put(key, cs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002544 } else {
2545 if (verifyPreloadConfig(
2546 changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2547 if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2548 // If this resource does not vary based on layout direction,
2549 // we can put it in all of the preload maps.
2550 sPreloadedDrawables[0].put(key, cs);
2551 sPreloadedDrawables[1].put(key, cs);
2552 } else {
2553 // Otherwise, only in the layout dir we loaded it for.
2554 sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
2557 }
Alan Viverette52b999f2014-03-24 18:00:26 -07002558 } else {
2559 synchronized (mAccessLock) {
Alan Viverettee54d2452015-05-06 10:41:43 -07002560 caches.put(key, theme, cs, usesTheme);
Alan Viverette52b999f2014-03-24 18:00:26 -07002561 }
2562 }
2563 }
2564
2565 /**
2566 * Loads a drawable from XML or resources stream.
2567 */
2568 private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2569 if (value.string == null) {
Alan Viverette0810b632014-05-01 14:42:56 -07002570 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002571 + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
Alan Viverette52b999f2014-03-24 18:00:26 -07002572 }
2573
2574 final String file = value.string.toString();
2575
2576 if (TRACE_FOR_MISS_PRELOAD) {
2577 // Log only framework resources
2578 if ((id >>> 24) == 0x1) {
2579 final String name = getResourceName(id);
2580 if (name != null) {
2581 Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2582 + ": " + name + " at " + file);
2583 }
2584 }
2585 }
2586
2587 if (DEBUG_LOAD) {
2588 Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2589 }
2590
2591 final Drawable dr;
2592
2593 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2594 try {
2595 if (file.endsWith(".xml")) {
2596 final XmlResourceParser rp = loadXmlResourceParser(
2597 file, id, value.assetCookie, "drawable");
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002598 dr = Drawable.createFromXml(this, rp, theme);
Alan Viverette52b999f2014-03-24 18:00:26 -07002599 rp.close();
2600 } else {
2601 final InputStream is = mAssets.openNonAsset(
2602 value.assetCookie, file, AssetManager.ACCESS_STREAMING);
Alan Viverette6dbe51b2014-06-02 16:39:04 -07002603 dr = Drawable.createFromResourceStream(this, value, is, file, null);
Alan Viverette52b999f2014-03-24 18:00:26 -07002604 is.close();
2605 }
2606 } catch (Exception e) {
2607 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2608 final NotFoundException rnf = new NotFoundException(
2609 "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2610 rnf.initCause(e);
2611 throw rnf;
2612 }
2613 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2614
2615 return dr;
2616 }
2617
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002618 /**
2619 * Given the value and id, we can get the XML filename as in value.data, based on that, we
2620 * first try to load CSL from the cache. If not found, try to get from the constant state.
2621 * Last, parse the XML and generate the CSL.
2622 */
2623 private ComplexColor loadComplexColorFromName(Theme theme, TypedValue value, int id) {
2624 final long key = (((long) value.assetCookie) << 32) | value.data;
2625 final ConfigurationBoundResourceCache<ComplexColor> cache = mComplexColorCache;
2626 ComplexColor complexColor = cache.getInstance(key, theme);
2627 if (complexColor != null) {
2628 return complexColor;
2629 }
2630
2631 final android.content.res.ConstantState<ComplexColor> factory =
2632 sPreloadedComplexColors.get(key);
2633
2634 if (factory != null) {
2635 complexColor = factory.newInstance(this, theme);
2636 }
2637 if (complexColor == null) {
2638 complexColor = loadComplexColorForCookie(value, id, theme);
2639 }
2640
2641 if (complexColor != null) {
2642 if (mPreloading) {
2643 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2644 "color")) {
2645 sPreloadedComplexColors.put(key, complexColor.getConstantState());
2646 }
2647 } else {
2648 cache.put(key, theme, complexColor.getConstantState());
2649 }
2650 }
2651 return complexColor;
2652 }
2653
2654 @Nullable
2655 public ComplexColor loadComplexColor(@NonNull TypedValue value, int id, Theme theme) {
2656 if (TRACE_FOR_PRELOAD) {
2657 // Log only framework resources
2658 if ((id >>> 24) == 0x1) {
2659 final String name = getResourceName(id);
2660 if (name != null) android.util.Log.d("loadComplexColor", name);
2661 }
2662 }
2663
2664 final long key = (((long) value.assetCookie) << 32) | value.data;
2665
2666 // Handle inline color definitions.
2667 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2668 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2669 return getColorStateListFromInt(value, key);
2670 }
2671
2672 final String file = value.string.toString();
2673
2674 ComplexColor complexColor;
2675 if (file.endsWith(".xml")) {
2676 try {
2677 complexColor = loadComplexColorFromName(theme, value, id);
2678 } catch (Exception e) {
2679 final NotFoundException rnf = new NotFoundException(
2680 "File " + file + " from complex color resource ID #0x"
2681 + Integer.toHexString(id));
2682 rnf.initCause(e);
2683 throw rnf;
2684 }
2685 } else {
2686 throw new NotFoundException(
2687 "File " + file + " from drawable resource ID #0x"
2688 + Integer.toHexString(id) + ": .xml extension required");
2689 }
2690
2691 return complexColor;
2692 }
2693
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002694 @Nullable
2695 ColorStateList loadColorStateList(TypedValue value, int id, Theme theme)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 throws NotFoundException {
2697 if (TRACE_FOR_PRELOAD) {
2698 // Log only framework resources
2699 if ((id >>> 24) == 0x1) {
2700 final String name = getResourceName(id);
2701 if (name != null) android.util.Log.d("PreloadColorStateList", name);
2702 }
2703 }
2704
Romain Guy5d911c32012-04-12 16:25:17 -07002705 final long key = (((long) value.assetCookie) << 32) | value.data;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002707 // Handle inline color definitions.
2708 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2709 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002710 return getColorStateListFromInt(value, key);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002713 ComplexColor complexColor = loadComplexColorFromName(theme, value, id);
2714 if (complexColor != null && complexColor instanceof ColorStateList) {
2715 return (ColorStateList) complexColor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002718 throw new NotFoundException(
2719 "Can't find ColorStateList from drawable resource ID #0x"
2720 + Integer.toHexString(id));
2721 }
2722
2723 @NonNull
2724 private ColorStateList getColorStateListFromInt(@NonNull TypedValue value, long key) {
2725 ColorStateList csl;
2726 final android.content.res.ConstantState<ComplexColor> factory =
2727 sPreloadedComplexColors.get(key);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002728 if (factory != null) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002729 return (ColorStateList) factory.newInstance();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
2731
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002732 csl = ColorStateList.valueOf(value.data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002734 if (mPreloading) {
2735 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2736 "color")) {
2737 sPreloadedComplexColors.put(key, csl.getConstantState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 }
2739 }
2740
2741 return csl;
2742 }
2743
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002744 /**
2745 * Load a ComplexColor based on the XML file content. The result can be a GradientColor or
2746 * ColorStateList. Note that pure color will be wrapped into a ColorStateList.
2747 *
2748 * We deferred the parser creation to this function b/c we need to differentiate b/t gradient
2749 * and selector tag.
2750 *
2751 * @return a ComplexColor (GradientColor or ColorStateList) based on the XML file content.
2752 */
2753 @Nullable
2754 private ComplexColor loadComplexColorForCookie(TypedValue value, int id, Theme theme) {
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002755 if (value.string == null) {
Alan Viverette6bbb47b2015-01-05 18:12:44 -08002756 throw new UnsupportedOperationException(
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002757 "Can't convert to ComplexColor: type=0x" + value.type);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002758 }
2759
2760 final String file = value.string.toString();
2761
2762 if (TRACE_FOR_MISS_PRELOAD) {
2763 // Log only framework resources
2764 if ((id >>> 24) == 0x1) {
2765 final String name = getResourceName(id);
2766 if (name != null) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002767 Log.d(TAG, "Loading framework ComplexColor #" + Integer.toHexString(id)
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002768 + ": " + name + " at " + file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 }
2770 }
2771 }
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002772
2773 if (DEBUG_LOAD) {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002774 Log.v(TAG, "Loading ComplexColor for cookie " + value.assetCookie + ": " + file);
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002775 }
2776
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002777 ComplexColor complexColor = null;
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002778
2779 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2780 if (file.endsWith(".xml")) {
2781 try {
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002782 final XmlResourceParser parser = loadXmlResourceParser(
2783 file, id, value.assetCookie, "ComplexColor");
2784
2785 final AttributeSet attrs = Xml.asAttributeSet(parser);
2786 int type;
2787 while ((type = parser.next()) != XmlPullParser.START_TAG
2788 && type != XmlPullParser.END_DOCUMENT) {
2789 // Seek parser to start tag.
2790 }
2791 if (type != XmlPullParser.START_TAG) {
2792 throw new XmlPullParserException("No start tag found");
2793 }
2794
2795 final String name = parser.getName();
2796 if (name.equals("gradient")) {
2797 complexColor = GradientColor.createFromXmlInner(this, parser, attrs, theme);
2798 } else if (name.equals("selector")) {
2799 complexColor = ColorStateList.createFromXmlInner(this, parser, attrs, theme);
2800 }
2801 parser.close();
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002802 } catch (Exception e) {
2803 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2804 final NotFoundException rnf = new NotFoundException(
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002805 "File " + file + " from ComplexColor resource ID #0x"
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002806 + Integer.toHexString(id));
2807 rnf.initCause(e);
2808 throw rnf;
2809 }
2810 } else {
2811 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2812 throw new NotFoundException(
2813 "File " + file + " from drawable resource ID #0x"
2814 + Integer.toHexString(id) + ": .xml extension required");
2815 }
2816 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2817
Teng-Hui Zhudbee9bb2015-12-15 11:01:27 -08002818 return complexColor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820
Alan Viverette10979612016-01-06 15:27:35 -05002821 /**
2822 * Loads an XML parser for the specified file.
2823 *
2824 * @param id the resource identifier for the file
2825 * @param type the type of resource (used for logging)
2826 * @return a parser for the specified XML file
2827 * @throws NotFoundException if the file could not be loaded
2828 */
2829 @NonNull
2830 XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 throws NotFoundException {
Alan Viverette4d07bc92015-11-16 10:19:12 -05002832 final TypedValue value = obtainTempTypedValue(id);
2833 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 if (value.type == TypedValue.TYPE_STRING) {
2835 return loadXmlResourceParser(value.string.toString(), id,
2836 value.assetCookie, type);
2837 }
Alan Viverette4d07bc92015-11-16 10:19:12 -05002838 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
2839 + " type #0x" + Integer.toHexString(value.type) + " is not valid");
2840 } finally {
2841 releaseTempTypedValue(value);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 }
2843 }
Alan Viverette10979612016-01-06 15:27:35 -05002844
2845 /**
2846 * Loads an XML parser for the specified file.
2847 *
2848 * @param file the path for the XML file to parse
2849 * @param id the resource identifier for the file
2850 * @param assetCookie the asset cookie for the file
2851 * @param type the type of resource (used for logging)
2852 * @return a parser for the specified XML file
2853 * @throws NotFoundException if the file could not be loaded
2854 */
2855 @NonNull
2856 XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id,
2857 int assetCookie, @NonNull String type) throws NotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 if (id != 0) {
2859 try {
Alan Viverette5c64b952016-02-28 15:16:05 -05002860 synchronized (mCachedXmlBlocks) {
2861 final int[] cachedXmlBlockCookies = mCachedXmlBlockCookies;
2862 final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
2863 final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 // First see if this block is in our cache.
Alan Viverette10979612016-01-06 15:27:35 -05002865 final int num = cachedXmlBlockFiles.length;
2866 for (int i = 0; i < num; i++) {
Alan Viverette5c64b952016-02-28 15:16:05 -05002867 if (cachedXmlBlockCookies[i] == assetCookie && cachedXmlBlockFiles[i] != null
Alan Viverette10979612016-01-06 15:27:35 -05002868 && cachedXmlBlockFiles[i].equals(file)) {
2869 return cachedXmlBlocks[i].newParser();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871 }
2872
2873 // Not in the cache, create a new block and put it at
2874 // the next slot in the cache.
Alan Viverette10979612016-01-06 15:27:35 -05002875 final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 if (block != null) {
Alan Viverette10979612016-01-06 15:27:35 -05002877 final int pos = (mLastCachedXmlBlockIndex + 1) % num;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 mLastCachedXmlBlockIndex = pos;
Alan Viverette10979612016-01-06 15:27:35 -05002879 final XmlBlock oldBlock = cachedXmlBlocks[pos];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 if (oldBlock != null) {
2881 oldBlock.close();
2882 }
Alan Viverette5c64b952016-02-28 15:16:05 -05002883 cachedXmlBlockCookies[pos] = assetCookie;
Alan Viverette10979612016-01-06 15:27:35 -05002884 cachedXmlBlockFiles[pos] = file;
2885 cachedXmlBlocks[pos] = block;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 return block.newParser();
2887 }
2888 }
2889 } catch (Exception e) {
Alan Viverette10979612016-01-06 15:27:35 -05002890 final NotFoundException rnf = new NotFoundException("File " + file
2891 + " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 rnf.initCause(e);
2893 throw rnf;
2894 }
2895 }
2896
Alan Viverette10979612016-01-06 15:27:35 -05002897 throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 + Integer.toHexString(id));
2899 }
2900
Alan Viverette45c4bbb2015-01-05 14:59:19 -08002901 /**
2902 * Obtains styled attributes from the theme, if available, or unstyled
2903 * resources if the theme is null.
2904 *
2905 * @hide
2906 */
2907 public static TypedArray obtainAttributes(
2908 Resources res, Theme theme, AttributeSet set, int[] attrs) {
2909 if (theme == null) {
2910 return res.obtainAttributes(set, attrs);
2911 }
2912 return theme.obtainStyledAttributes(set, attrs, 0, 0);
2913 }
2914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 private Resources() {
2916 mAssets = AssetManager.getSystem();
Alan Viverette02fc5fe2015-08-27 13:16:09 -04002917 mClassLoader = ClassLoader.getSystemClassLoader();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 // NOTE: Intentionally leaving this uninitialized (all values set
2919 // to zero), so that anyone who tries to do something that requires
2920 // metrics will get a very wrong value.
2921 mConfiguration.setToDefaults();
2922 mMetrics.setToDefaults();
2923 updateConfiguration(null, null);
2924 mAssets.ensureStringBlocks();
2925 }
2926}