blob: aaa8b8c9cc12114013cf15b90171d8e5152bf3eb [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 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.view;
18
Romain Guy9c1223a2011-05-17 14:25:49 -070019import android.graphics.Canvas;
20import android.os.Handler;
21import android.os.Message;
Romain Guy09f7b932013-04-10 11:42:44 -070022import android.os.Trace;
Romain Guy9c1223a2011-05-17 14:25:49 -070023import android.widget.FrameLayout;
Gilles Debunne30301932010-06-16 18:32:00 -070024import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.Context;
28import android.content.res.TypedArray;
29import android.content.res.XmlResourceParser;
30import android.util.AttributeSet;
31import android.util.Xml;
32
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import java.io.IOException;
34import java.lang.reflect.Constructor;
35import java.util.HashMap;
36
37/**
Scott Main93dc6422012-02-24 12:04:06 -080038 * Instantiates a layout XML file into its corresponding {@link android.view.View}
39 * objects. It is never used directly. Instead, use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 * {@link android.app.Activity#getLayoutInflater()} or
41 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
42 * that is already hooked up to the current context and correctly configured
43 * for the device you are running on. For example:
44 *
45 * <pre>LayoutInflater inflater = (LayoutInflater)context.getSystemService
Christian Mehlmauerbd6fda12011-01-08 18:22:20 +010046 * (Context.LAYOUT_INFLATER_SERVICE);</pre>
Dave Burke579e1402012-10-18 20:41:55 -070047 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048 * <p>
49 * To create a new LayoutInflater with an additional {@link Factory} for your
50 * own views, you can use {@link #cloneInContext} to clone an existing
51 * ViewFactory, and then call {@link #setFactory} on it to include your
52 * Factory.
Dave Burke579e1402012-10-18 20:41:55 -070053 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 * <p>
55 * For performance reasons, view inflation relies heavily on pre-processing of
56 * XML files that is done at build time. Therefore, it is not currently possible
57 * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
58 * it only works with an XmlPullParser returned from a compiled resource
59 * (R.<em>something</em> file.)
Dave Burke579e1402012-10-18 20:41:55 -070060 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 * @see Context#getSystemService
62 */
63public abstract class LayoutInflater {
64 private final boolean DEBUG = false;
65
66 /**
67 * This field should be made private, so it is hidden from the SDK.
68 * {@hide}
69 */
70 protected final Context mContext;
71
72 // these are optional, set by the caller
73 private boolean mFactorySet;
74 private Factory mFactory;
Dianne Hackborn625ac272010-09-17 18:29:22 -070075 private Factory2 mFactory2;
Dianne Hackborn420829e2011-01-28 11:30:35 -080076 private Factory2 mPrivateFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 private Filter mFilter;
78
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070079 final Object[] mConstructorArgs = new Object[2];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -070081 static final Class<?>[] mConstructorSignature = new Class[] {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 Context.class, AttributeSet.class};
83
Gilles Debunne30301932010-06-16 18:32:00 -070084 private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
85 new HashMap<String, Constructor<? extends View>>();
Dave Burke579e1402012-10-18 20:41:55 -070086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private HashMap<String, Boolean> mFilterMap;
88
89 private static final String TAG_MERGE = "merge";
90 private static final String TAG_INCLUDE = "include";
Romain Guy9c1223a2011-05-17 14:25:49 -070091 private static final String TAG_1995 = "blink";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private static final String TAG_REQUEST_FOCUS = "requestFocus";
93
Alan Viveretteef259e42014-01-24 17:20:12 -080094 private static final int[] ATTRS_THEME = new int[] {
95 com.android.internal.R.attr.theme };
Alan Viverette24927f22014-01-07 17:28:48 -080096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 /**
98 * Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed
99 * to be inflated.
Dave Burke579e1402012-10-18 20:41:55 -0700100 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 */
102 public interface Filter {
103 /**
104 * Hook to allow clients of the LayoutInflater to restrict the set of Views
105 * that are allowed to be inflated.
Dave Burke579e1402012-10-18 20:41:55 -0700106 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 * @param clazz The class object for the View that is about to be inflated
Dave Burke579e1402012-10-18 20:41:55 -0700108 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 * @return True if this class is allowed to be inflated, or false otherwise
110 */
Gilles Debunnee6ac8b92010-06-17 10:55:04 -0700111 @SuppressWarnings("unchecked")
112 boolean onLoadClass(Class clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 }
Dave Burke579e1402012-10-18 20:41:55 -0700114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 public interface Factory {
116 /**
117 * Hook you can supply that is called when inflating from a LayoutInflater.
118 * You can use this to customize the tag names available in your XML
119 * layout files.
Dave Burke579e1402012-10-18 20:41:55 -0700120 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * <p>
122 * Note that it is good practice to prefix these custom names with your
123 * package (i.e., com.coolcompany.apps) to avoid conflicts with system
124 * names.
Dave Burke579e1402012-10-18 20:41:55 -0700125 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 * @param name Tag name to be inflated.
127 * @param context The context the view is being created in.
128 * @param attrs Inflation attributes as specified in XML file.
Dave Burke579e1402012-10-18 20:41:55 -0700129 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 * @return View Newly created view. Return null for the default
131 * behavior.
132 */
133 public View onCreateView(String name, Context context, AttributeSet attrs);
134 }
135
Dianne Hackborn625ac272010-09-17 18:29:22 -0700136 public interface Factory2 extends Factory {
137 /**
138 * Version of {@link #onCreateView(String, Context, AttributeSet)}
139 * that also supplies the parent that the view created view will be
140 * placed in.
141 *
142 * @param parent The parent that the created view will be placed
143 * in; <em>note that this may be null</em>.
144 * @param name Tag name to be inflated.
145 * @param context The context the view is being created in.
146 * @param attrs Inflation attributes as specified in XML file.
147 *
148 * @return View Newly created view. Return null for the default
149 * behavior.
150 */
151 public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
152 }
153
154 private static class FactoryMerger implements Factory2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private final Factory mF1, mF2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700156 private final Factory2 mF12, mF22;
Dave Burke579e1402012-10-18 20:41:55 -0700157
Dianne Hackborn625ac272010-09-17 18:29:22 -0700158 FactoryMerger(Factory f1, Factory2 f12, Factory f2, Factory2 f22) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 mF1 = f1;
160 mF2 = f2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700161 mF12 = f12;
162 mF22 = f22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 }
Dave Burke579e1402012-10-18 20:41:55 -0700164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 public View onCreateView(String name, Context context, AttributeSet attrs) {
166 View v = mF1.onCreateView(name, context, attrs);
167 if (v != null) return v;
168 return mF2.onCreateView(name, context, attrs);
169 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700170
171 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
172 View v = mF12 != null ? mF12.onCreateView(parent, name, context, attrs)
173 : mF1.onCreateView(name, context, attrs);
174 if (v != null) return v;
175 return mF22 != null ? mF22.onCreateView(parent, name, context, attrs)
176 : mF2.onCreateView(name, context, attrs);
177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 }
Dave Burke579e1402012-10-18 20:41:55 -0700179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 /**
181 * Create a new LayoutInflater instance associated with a particular Context.
182 * Applications will almost always want to use
183 * {@link Context#getSystemService Context.getSystemService()} to retrieve
184 * the standard {@link Context#LAYOUT_INFLATER_SERVICE Context.INFLATER_SERVICE}.
Dave Burke579e1402012-10-18 20:41:55 -0700185 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 * @param context The Context in which this LayoutInflater will create its
187 * Views; most importantly, this supplies the theme from which the default
188 * values for their attributes are retrieved.
189 */
190 protected LayoutInflater(Context context) {
191 mContext = context;
192 }
193
194 /**
195 * Create a new LayoutInflater instance that is a copy of an existing
196 * LayoutInflater, optionally with its Context changed. For use in
197 * implementing {@link #cloneInContext}.
Dave Burke579e1402012-10-18 20:41:55 -0700198 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 * @param original The original LayoutInflater to copy.
200 * @param newContext The new Context to use.
201 */
202 protected LayoutInflater(LayoutInflater original, Context newContext) {
203 mContext = newContext;
204 mFactory = original.mFactory;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700205 mFactory2 = original.mFactory2;
Dianne Hackborn420829e2011-01-28 11:30:35 -0800206 mPrivateFactory = original.mPrivateFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 mFilter = original.mFilter;
208 }
Dave Burke579e1402012-10-18 20:41:55 -0700209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 /**
211 * Obtains the LayoutInflater from the given context.
212 */
213 public static LayoutInflater from(Context context) {
214 LayoutInflater LayoutInflater =
215 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
216 if (LayoutInflater == null) {
217 throw new AssertionError("LayoutInflater not found.");
218 }
219 return LayoutInflater;
220 }
221
222 /**
223 * Create a copy of the existing LayoutInflater object, with the copy
224 * pointing to a different Context than the original. This is used by
225 * {@link ContextThemeWrapper} to create a new LayoutInflater to go along
226 * with the new Context theme.
Dave Burke579e1402012-10-18 20:41:55 -0700227 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 * @param newContext The new Context to associate with the new LayoutInflater.
229 * May be the same as the original Context if desired.
Dave Burke579e1402012-10-18 20:41:55 -0700230 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 * @return Returns a brand spanking new LayoutInflater object associated with
232 * the given Context.
233 */
234 public abstract LayoutInflater cloneInContext(Context newContext);
Dave Burke579e1402012-10-18 20:41:55 -0700235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 /**
237 * Return the context we are running in, for access to resources, class
238 * loader, etc.
239 */
240 public Context getContext() {
241 return mContext;
242 }
243
244 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700245 * Return the current {@link Factory} (or null). This is called on each element
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 * name. If the factory returns a View, add that to the hierarchy. If it
247 * returns null, proceed to call onCreateView(name).
248 */
249 public final Factory getFactory() {
250 return mFactory;
251 }
252
253 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700254 * Return the current {@link Factory2}. Returns null if no factory is set
255 * or the set factory does not implement the {@link Factory2} interface.
256 * This is called on each element
257 * name. If the factory returns a View, add that to the hierarchy. If it
258 * returns null, proceed to call onCreateView(name).
259 */
260 public final Factory2 getFactory2() {
261 return mFactory2;
262 }
263
264 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 * Attach a custom Factory interface for creating views while using
266 * this LayoutInflater. This must not be null, and can only be set once;
267 * after setting, you can not change the factory. This is
268 * called on each element name as the xml is parsed. If the factory returns
269 * a View, that is added to the hierarchy. If it returns null, the next
270 * factory default {@link #onCreateView} method is called.
Dave Burke579e1402012-10-18 20:41:55 -0700271 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 * <p>If you have an existing
273 * LayoutInflater and want to add your own factory to it, use
274 * {@link #cloneInContext} to clone the existing instance and then you
275 * can use this function (once) on the returned new instance. This will
276 * merge your own factory with whatever factory the original instance is
277 * using.
278 */
279 public void setFactory(Factory factory) {
280 if (mFactorySet) {
281 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
282 }
283 if (factory == null) {
284 throw new NullPointerException("Given factory can not be null");
285 }
286 mFactorySet = true;
287 if (mFactory == null) {
288 mFactory = factory;
289 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700290 mFactory = new FactoryMerger(factory, null, mFactory, mFactory2);
291 }
292 }
293
294 /**
295 * Like {@link #setFactory}, but allows you to set a {@link Factory2}
296 * interface.
297 */
298 public void setFactory2(Factory2 factory) {
299 if (mFactorySet) {
300 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
301 }
302 if (factory == null) {
303 throw new NullPointerException("Given factory can not be null");
304 }
305 mFactorySet = true;
306 if (mFactory == null) {
307 mFactory = mFactory2 = factory;
308 } else {
309 mFactory = new FactoryMerger(factory, factory, mFactory, mFactory2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311 }
312
313 /**
Dianne Hackborn420829e2011-01-28 11:30:35 -0800314 * @hide for use by framework
315 */
316 public void setPrivateFactory(Factory2 factory) {
317 mPrivateFactory = factory;
318 }
319
320 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 * @return The {@link Filter} currently used by this LayoutInflater to restrict the set of Views
322 * that are allowed to be inflated.
323 */
324 public Filter getFilter() {
325 return mFilter;
326 }
Dave Burke579e1402012-10-18 20:41:55 -0700327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 /**
329 * Sets the {@link Filter} to by this LayoutInflater. If a view is attempted to be inflated
330 * which is not allowed by the {@link Filter}, the {@link #inflate(int, ViewGroup)} call will
331 * throw an {@link InflateException}. This filter will replace any previous filter set on this
332 * LayoutInflater.
Dave Burke579e1402012-10-18 20:41:55 -0700333 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 * @param filter The Filter which restricts the set of Views that are allowed to be inflated.
335 * This filter will replace any previous filter set on this LayoutInflater.
336 */
337 public void setFilter(Filter filter) {
338 mFilter = filter;
339 if (filter != null) {
340 mFilterMap = new HashMap<String, Boolean>();
341 }
342 }
343
344 /**
345 * Inflate a new view hierarchy from the specified xml resource. Throws
346 * {@link InflateException} if there is an error.
Dave Burke579e1402012-10-18 20:41:55 -0700347 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 * @param resource ID for an XML layout resource to load (e.g.,
349 * <code>R.layout.main_page</code>)
350 * @param root Optional view to be the parent of the generated hierarchy.
351 * @return The root View of the inflated hierarchy. If root was supplied,
352 * this is the root View; otherwise it is the root of the inflated
353 * XML file.
354 */
355 public View inflate(int resource, ViewGroup root) {
356 return inflate(resource, root, root != null);
357 }
358
359 /**
360 * Inflate a new view hierarchy from the specified xml node. Throws
361 * {@link InflateException} if there is an error. *
362 * <p>
363 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
364 * reasons, view inflation relies heavily on pre-processing of XML files
365 * that is done at build time. Therefore, it is not currently possible to
366 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
Dave Burke579e1402012-10-18 20:41:55 -0700367 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 * @param parser XML dom node containing the description of the view
369 * hierarchy.
370 * @param root Optional view to be the parent of the generated hierarchy.
371 * @return The root View of the inflated hierarchy. If root was supplied,
372 * this is the root View; otherwise it is the root of the inflated
373 * XML file.
374 */
375 public View inflate(XmlPullParser parser, ViewGroup root) {
376 return inflate(parser, root, root != null);
377 }
378
379 /**
380 * Inflate a new view hierarchy from the specified xml resource. Throws
381 * {@link InflateException} if there is an error.
Dave Burke579e1402012-10-18 20:41:55 -0700382 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 * @param resource ID for an XML layout resource to load (e.g.,
384 * <code>R.layout.main_page</code>)
385 * @param root Optional view to be the parent of the generated hierarchy (if
386 * <em>attachToRoot</em> is true), or else simply an object that
387 * provides a set of LayoutParams values for root of the returned
388 * hierarchy (if <em>attachToRoot</em> is false.)
389 * @param attachToRoot Whether the inflated hierarchy should be attached to
390 * the root parameter? If false, root is only used to create the
391 * correct subclass of LayoutParams for the root view in the XML.
392 * @return The root View of the inflated hierarchy. If root was supplied and
393 * attachToRoot is true, this is root; otherwise it is the root of
394 * the inflated XML file.
395 */
396 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
397 if (DEBUG) System.out.println("INFLATING from resource: " + resource);
398 XmlResourceParser parser = getContext().getResources().getLayout(resource);
399 try {
400 return inflate(parser, root, attachToRoot);
401 } finally {
402 parser.close();
403 }
404 }
405
406 /**
407 * Inflate a new view hierarchy from the specified XML node. Throws
408 * {@link InflateException} if there is an error.
409 * <p>
410 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
411 * reasons, view inflation relies heavily on pre-processing of XML files
412 * that is done at build time. Therefore, it is not currently possible to
413 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
Dave Burke579e1402012-10-18 20:41:55 -0700414 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 * @param parser XML dom node containing the description of the view
416 * hierarchy.
417 * @param root Optional view to be the parent of the generated hierarchy (if
418 * <em>attachToRoot</em> is true), or else simply an object that
419 * provides a set of LayoutParams values for root of the returned
420 * hierarchy (if <em>attachToRoot</em> is false.)
421 * @param attachToRoot Whether the inflated hierarchy should be attached to
422 * the root parameter? If false, root is only used to create the
423 * correct subclass of LayoutParams for the root view in the XML.
424 * @return The root View of the inflated hierarchy. If root was supplied and
425 * attachToRoot is true, this is root; otherwise it is the root of
426 * the inflated XML file.
427 */
428 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
429 synchronized (mConstructorArgs) {
Romain Guy09f7b932013-04-10 11:42:44 -0700430 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 final AttributeSet attrs = Xml.asAttributeSet(parser);
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700433 Context lastContext = (Context)mConstructorArgs[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 mConstructorArgs[0] = mContext;
435 View result = root;
436
437 try {
438 // Look for the root node.
439 int type;
440 while ((type = parser.next()) != XmlPullParser.START_TAG &&
441 type != XmlPullParser.END_DOCUMENT) {
442 // Empty
443 }
444
445 if (type != XmlPullParser.START_TAG) {
446 throw new InflateException(parser.getPositionDescription()
447 + ": No start tag found!");
448 }
449
450 final String name = parser.getName();
Dave Burke579e1402012-10-18 20:41:55 -0700451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 if (DEBUG) {
453 System.out.println("**************************");
454 System.out.println("Creating root view: "
455 + name);
456 System.out.println("**************************");
457 }
458
459 if (TAG_MERGE.equals(name)) {
460 if (root == null || !attachToRoot) {
461 throw new InflateException("<merge /> can be used only with a valid "
462 + "ViewGroup root and attachToRoot=true");
463 }
464
Alan Viverette24927f22014-01-07 17:28:48 -0800465 rInflate(parser, root, attrs, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 } else {
467 // Temp is the root view that was found in the xml
Alan Viverette24927f22014-01-07 17:28:48 -0800468 final View temp = createViewFromTag(root, name, attrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469
470 ViewGroup.LayoutParams params = null;
471
472 if (root != null) {
473 if (DEBUG) {
474 System.out.println("Creating params from root: " +
475 root);
476 }
477 // Create layout params that match root, if supplied
478 params = root.generateLayoutParams(attrs);
479 if (!attachToRoot) {
480 // Set the layout params for temp if we are not
481 // attaching. (If we are, we use addView, below)
482 temp.setLayoutParams(params);
483 }
484 }
485
486 if (DEBUG) {
487 System.out.println("-----> start inflating children");
488 }
489 // Inflate all children under temp
Alan Viverette24927f22014-01-07 17:28:48 -0800490 rInflate(parser, temp, attrs, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 if (DEBUG) {
492 System.out.println("-----> done inflating children");
493 }
494
495 // We are supposed to attach all the views we found (int temp)
496 // to root. Do that now.
497 if (root != null && attachToRoot) {
498 root.addView(temp, params);
499 }
500
501 // Decide whether to return the root that was passed in or the
502 // top view found in xml.
503 if (root == null || !attachToRoot) {
504 result = temp;
505 }
506 }
507
508 } catch (XmlPullParserException e) {
509 InflateException ex = new InflateException(e.getMessage());
510 ex.initCause(e);
511 throw ex;
512 } catch (IOException e) {
513 InflateException ex = new InflateException(
514 parser.getPositionDescription()
515 + ": " + e.getMessage());
516 ex.initCause(e);
517 throw ex;
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700518 } finally {
519 // Don't retain static reference on context.
520 mConstructorArgs[0] = lastContext;
521 mConstructorArgs[1] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
Romain Guy09f7b932013-04-10 11:42:44 -0700524 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 return result;
527 }
528 }
529
530 /**
531 * Low-level function for instantiating a view by name. This attempts to
532 * instantiate a view class of the given <var>name</var> found in this
533 * LayoutInflater's ClassLoader.
Dave Burke579e1402012-10-18 20:41:55 -0700534 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 * <p>
536 * There are two things that can happen in an error case: either the
537 * exception describing the error will be thrown, or a null will be
538 * returned. You must deal with both possibilities -- the former will happen
539 * the first time createView() is called for a class of a particular name,
540 * the latter every time there-after for that class name.
Dave Burke579e1402012-10-18 20:41:55 -0700541 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 * @param name The full name of the class to be instantiated.
543 * @param attrs The XML attributes supplied for this instance.
Dave Burke579e1402012-10-18 20:41:55 -0700544 *
Gilles Debunne30301932010-06-16 18:32:00 -0700545 * @return View The newly instantiated view, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 */
547 public final View createView(String name, String prefix, AttributeSet attrs)
548 throws ClassNotFoundException, InflateException {
Gilles Debunne30301932010-06-16 18:32:00 -0700549 Constructor<? extends View> constructor = sConstructorMap.get(name);
550 Class<? extends View> clazz = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551
552 try {
Romain Guy09f7b932013-04-10 11:42:44 -0700553 Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 if (constructor == null) {
556 // Class not found in the cache, see if it's real, and try to add it
Romain Guyd03b8802009-09-16 14:36:16 -0700557 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700558 prefix != null ? (prefix + name) : name).asSubclass(View.class);
Dave Burke579e1402012-10-18 20:41:55 -0700559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 if (mFilter != null && clazz != null) {
561 boolean allowed = mFilter.onLoadClass(clazz);
562 if (!allowed) {
563 failNotAllowed(name, prefix, attrs);
564 }
565 }
566 constructor = clazz.getConstructor(mConstructorSignature);
567 sConstructorMap.put(name, constructor);
568 } else {
569 // If we have a filter, apply it to cached constructor
570 if (mFilter != null) {
571 // Have we seen this name before?
572 Boolean allowedState = mFilterMap.get(name);
573 if (allowedState == null) {
574 // New class -- remember whether it is allowed
Romain Guyd03b8802009-09-16 14:36:16 -0700575 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700576 prefix != null ? (prefix + name) : name).asSubclass(View.class);
Dave Burke579e1402012-10-18 20:41:55 -0700577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
579 mFilterMap.put(name, allowed);
580 if (!allowed) {
581 failNotAllowed(name, prefix, attrs);
582 }
583 } else if (allowedState.equals(Boolean.FALSE)) {
584 failNotAllowed(name, prefix, attrs);
585 }
586 }
587 }
588
589 Object[] args = mConstructorArgs;
590 args[1] = attrs;
Jeff Sharkeyb27b7a12012-04-02 21:07:29 -0700591
592 final View view = constructor.newInstance(args);
593 if (view instanceof ViewStub) {
594 // always use ourselves when inflating ViewStub later
595 final ViewStub viewStub = (ViewStub) view;
596 viewStub.setLayoutInflater(this);
597 }
598 return view;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599
600 } catch (NoSuchMethodException e) {
601 InflateException ie = new InflateException(attrs.getPositionDescription()
602 + ": Error inflating class "
603 + (prefix != null ? (prefix + name) : name));
604 ie.initCause(e);
605 throw ie;
606
Gilles Debunne30301932010-06-16 18:32:00 -0700607 } catch (ClassCastException e) {
608 // If loaded class is not a View subclass
609 InflateException ie = new InflateException(attrs.getPositionDescription()
610 + ": Class is not a View "
611 + (prefix != null ? (prefix + name) : name));
612 ie.initCause(e);
613 throw ie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 } catch (ClassNotFoundException e) {
615 // If loadClass fails, we should propagate the exception.
616 throw e;
617 } catch (Exception e) {
618 InflateException ie = new InflateException(attrs.getPositionDescription()
619 + ": Error inflating class "
Romain Guyd03b8802009-09-16 14:36:16 -0700620 + (clazz == null ? "<unknown>" : clazz.getName()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 ie.initCause(e);
622 throw ie;
Romain Guy09f7b932013-04-10 11:42:44 -0700623 } finally {
624 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626 }
627
628 /**
Gilles Debunne30301932010-06-16 18:32:00 -0700629 * Throw an exception because the specified class is not allowed to be inflated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 */
631 private void failNotAllowed(String name, String prefix, AttributeSet attrs) {
Romain Guy9c1223a2011-05-17 14:25:49 -0700632 throw new InflateException(attrs.getPositionDescription()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 + ": Class not allowed to be inflated "
634 + (prefix != null ? (prefix + name) : name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
637 /**
638 * This routine is responsible for creating the correct subclass of View
639 * given the xml element name. Override it to handle custom view objects. If
640 * you override this in your subclass be sure to call through to
641 * super.onCreateView(name) for names you do not recognize.
Dave Burke579e1402012-10-18 20:41:55 -0700642 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * @param name The fully qualified class name of the View to be create.
644 * @param attrs An AttributeSet of attributes to apply to the View.
Dave Burke579e1402012-10-18 20:41:55 -0700645 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * @return View The View created.
647 */
648 protected View onCreateView(String name, AttributeSet attrs)
649 throws ClassNotFoundException {
650 return createView(name, "android.view.", attrs);
651 }
652
Dianne Hackborn625ac272010-09-17 18:29:22 -0700653 /**
654 * Version of {@link #onCreateView(String, AttributeSet)} that also
Chet Haase430742f2013-04-12 11:18:36 -0700655 * takes the future parent of the view being constructed. The default
Dianne Hackborn625ac272010-09-17 18:29:22 -0700656 * implementation simply calls {@link #onCreateView(String, AttributeSet)}.
657 *
658 * @param parent The future parent of the returned view. <em>Note that
659 * this may be null.</em>
660 * @param name The fully qualified class name of the View to be create.
661 * @param attrs An AttributeSet of attributes to apply to the View.
662 *
663 * @return View The View created.
664 */
665 protected View onCreateView(View parent, String name, AttributeSet attrs)
666 throws ClassNotFoundException {
667 return onCreateView(name, attrs);
668 }
669
Alan Viverette24927f22014-01-07 17:28:48 -0800670 /**
671 * Creates a view from a tag name using the supplied attribute set.
672 * <p>
673 * If {@code inheritContext} is true and the parent is non-null, the view
674 * will be inflated in parent view's context. If the view specifies a
675 * &lt;theme&gt; attribute, the inflation context will be wrapped with the
676 * specified theme.
677 * <p>
678 * Note: Default visibility so the BridgeInflater can override it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 */
Alan Viverette24927f22014-01-07 17:28:48 -0800680 View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 if (name.equals("view")) {
682 name = attrs.getAttributeValue(null, "class");
683 }
684
Alan Viverette24927f22014-01-07 17:28:48 -0800685 Context viewContext;
686 if (parent != null && inheritContext) {
687 viewContext = parent.getContext();
688 } else {
689 viewContext = mContext;
690 }
691
692 // Apply a theme wrapper, if requested.
Alan Viveretteef259e42014-01-24 17:20:12 -0800693 final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
694 final int themeResId = ta.getResourceId(0, 0);
Alan Viverette24927f22014-01-07 17:28:48 -0800695 if (themeResId != 0) {
696 viewContext = new ContextThemeWrapper(viewContext, themeResId);
697 }
Alan Viveretteef259e42014-01-24 17:20:12 -0800698 ta.recycle();
Alan Viverette24927f22014-01-07 17:28:48 -0800699
700 if (name.equals(TAG_1995)) {
701 // Let's party like it's 1995!
702 return new BlinkLayout(viewContext, attrs);
703 }
704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 if (DEBUG) System.out.println("******** Creating view: " + name);
706
707 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700708 View view;
Alan Viverette24927f22014-01-07 17:28:48 -0800709 if (mFactory2 != null) {
710 view = mFactory2.onCreateView(parent, name, viewContext, attrs);
711 } else if (mFactory != null) {
712 view = mFactory.onCreateView(name, viewContext, attrs);
713 } else {
714 view = null;
715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716
Dianne Hackborn420829e2011-01-28 11:30:35 -0800717 if (view == null && mPrivateFactory != null) {
Alan Viverette24927f22014-01-07 17:28:48 -0800718 view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
Dianne Hackborn420829e2011-01-28 11:30:35 -0800719 }
Alan Viverette24927f22014-01-07 17:28:48 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (view == null) {
Alan Viverette24927f22014-01-07 17:28:48 -0800722 final Object lastContext = mConstructorArgs[0];
723 mConstructorArgs[0] = viewContext;
724 try {
725 if (-1 == name.indexOf('.')) {
726 view = onCreateView(parent, name, attrs);
727 } else {
728 view = createView(name, null, attrs);
729 }
730 } finally {
731 mConstructorArgs[0] = lastContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733 }
734
735 if (DEBUG) System.out.println("Created view is: " + view);
736 return view;
737
738 } catch (InflateException e) {
739 throw e;
740
741 } catch (ClassNotFoundException e) {
742 InflateException ie = new InflateException(attrs.getPositionDescription()
743 + ": Error inflating class " + name);
744 ie.initCause(e);
745 throw ie;
746
747 } catch (Exception e) {
748 InflateException ie = new InflateException(attrs.getPositionDescription()
749 + ": Error inflating class " + name);
750 ie.initCause(e);
751 throw ie;
752 }
753 }
754
755 /**
756 * Recursive method used to descend down the xml hierarchy and instantiate
757 * views, instantiate their children, and then call onFinishInflate().
Alan Viverette24927f22014-01-07 17:28:48 -0800758 *
759 * @param inheritContext Whether the root view should be inflated in its
760 * parent's context. This should be true when called inflating
761 * child views recursively, or false otherwise.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 */
Xavier Ducrohet7f9f99ea2011-08-11 10:16:17 -0700763 void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
Alan Viverette24927f22014-01-07 17:28:48 -0800764 boolean finishInflate, boolean inheritContext) throws XmlPullParserException,
765 IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
767 final int depth = parser.getDepth();
768 int type;
769
770 while (((type = parser.next()) != XmlPullParser.END_TAG ||
771 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
772
773 if (type != XmlPullParser.START_TAG) {
774 continue;
775 }
776
777 final String name = parser.getName();
Dave Burke579e1402012-10-18 20:41:55 -0700778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 if (TAG_REQUEST_FOCUS.equals(name)) {
780 parseRequestFocus(parser, parent);
781 } else if (TAG_INCLUDE.equals(name)) {
782 if (parser.getDepth() == 0) {
783 throw new InflateException("<include /> cannot be the root element");
784 }
Alan Viverette24927f22014-01-07 17:28:48 -0800785 parseInclude(parser, parent, attrs, inheritContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 } else if (TAG_MERGE.equals(name)) {
787 throw new InflateException("<merge /> must be the root element");
788 } else {
Alan Viverette24927f22014-01-07 17:28:48 -0800789 final View view = createViewFromTag(parent, name, attrs, inheritContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 final ViewGroup viewGroup = (ViewGroup) parent;
791 final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
Alan Viverette24927f22014-01-07 17:28:48 -0800792 rInflate(parser, view, attrs, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 viewGroup.addView(view, params);
794 }
795 }
796
Romain Guy9295ada2010-06-15 11:33:24 -0700797 if (finishInflate) parent.onFinishInflate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
799
800 private void parseRequestFocus(XmlPullParser parser, View parent)
801 throws XmlPullParserException, IOException {
802 int type;
803 parent.requestFocus();
804 final int currentDepth = parser.getDepth();
805 while (((type = parser.next()) != XmlPullParser.END_TAG ||
806 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
807 // Empty
808 }
809 }
810
Alan Viverette24927f22014-01-07 17:28:48 -0800811 private void parseInclude(XmlPullParser parser, View parent, AttributeSet attrs,
812 boolean inheritContext) throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 int type;
814
815 if (parent instanceof ViewGroup) {
816 final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
817 if (layout == 0) {
818 final String value = attrs.getAttributeValue(null, "layout");
819 if (value == null) {
820 throw new InflateException("You must specifiy a layout in the"
821 + " include tag: <include layout=\"@layout/layoutID\" />");
822 } else {
823 throw new InflateException("You must specifiy a valid layout "
824 + "reference. The layout ID " + value + " is not valid.");
825 }
826 } else {
827 final XmlResourceParser childParser =
828 getContext().getResources().getLayout(layout);
829
830 try {
831 final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
832
833 while ((type = childParser.next()) != XmlPullParser.START_TAG &&
834 type != XmlPullParser.END_DOCUMENT) {
835 // Empty.
836 }
837
838 if (type != XmlPullParser.START_TAG) {
839 throw new InflateException(childParser.getPositionDescription() +
840 ": No start tag found!");
841 }
842
843 final String childName = childParser.getName();
844
845 if (TAG_MERGE.equals(childName)) {
846 // Inflate all children.
Alan Viverette24927f22014-01-07 17:28:48 -0800847 rInflate(childParser, parent, childAttrs, false, inheritContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 } else {
Alan Viverette24927f22014-01-07 17:28:48 -0800849 final View view = createViewFromTag(parent, childName, childAttrs,
850 inheritContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 final ViewGroup group = (ViewGroup) parent;
852
853 // We try to load the layout params set in the <include /> tag. If
854 // they don't exist, we will rely on the layout params set in the
855 // included XML file.
Dave Burke579e1402012-10-18 20:41:55 -0700856 // During a layoutparams generation, a runtime exception is thrown
857 // if either layout_width or layout_height is missing. We catch
858 // this exception and set localParams accordingly: true means we
859 // successfully loaded layout params from the <include /> tag,
860 // false means we need to rely on the included layout params.
861 ViewGroup.LayoutParams params = null;
862 try {
863 params = group.generateLayoutParams(attrs);
864 } catch (RuntimeException e) {
865 params = group.generateLayoutParams(childAttrs);
866 } finally {
867 if (params != null) {
868 view.setLayoutParams(params);
869 }
870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871
872 // Inflate all children.
Alan Viverette24927f22014-01-07 17:28:48 -0800873 rInflate(childParser, view, childAttrs, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874
875 // Attempt to override the included layout's android:id with the
876 // one set on the <include /> tag itself.
877 TypedArray a = mContext.obtainStyledAttributes(attrs,
878 com.android.internal.R.styleable.View, 0, 0);
879 int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
880 // While we're at it, let's try to override android:visibility.
881 int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
882 a.recycle();
883
884 if (id != View.NO_ID) {
885 view.setId(id);
886 }
887
888 switch (visibility) {
889 case 0:
890 view.setVisibility(View.VISIBLE);
891 break;
892 case 1:
893 view.setVisibility(View.INVISIBLE);
894 break;
895 case 2:
896 view.setVisibility(View.GONE);
897 break;
898 }
899
900 group.addView(view);
901 }
902 } finally {
903 childParser.close();
904 }
905 }
906 } else {
907 throw new InflateException("<include /> can only be used inside of a ViewGroup");
908 }
909
910 final int currentDepth = parser.getDepth();
911 while (((type = parser.next()) != XmlPullParser.END_TAG ||
912 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
913 // Empty
914 }
Romain Guy9c1223a2011-05-17 14:25:49 -0700915 }
916
917 private static class BlinkLayout extends FrameLayout {
918 private static final int MESSAGE_BLINK = 0x42;
919 private static final int BLINK_DELAY = 500;
920
921 private boolean mBlink;
922 private boolean mBlinkState;
923 private final Handler mHandler;
924
925 public BlinkLayout(Context context, AttributeSet attrs) {
926 super(context, attrs);
927 mHandler = new Handler(new Handler.Callback() {
928 @Override
929 public boolean handleMessage(Message msg) {
930 if (msg.what == MESSAGE_BLINK) {
931 if (mBlink) {
932 mBlinkState = !mBlinkState;
933 makeBlink();
934 }
935 invalidate();
936 return true;
937 }
938 return false;
939 }
940 });
941 }
942
943 private void makeBlink() {
944 Message message = mHandler.obtainMessage(MESSAGE_BLINK);
945 mHandler.sendMessageDelayed(message, BLINK_DELAY);
946 }
947
948 @Override
949 protected void onAttachedToWindow() {
950 super.onAttachedToWindow();
951
952 mBlink = true;
953 mBlinkState = true;
954
955 makeBlink();
956 }
957
958 @Override
959 protected void onDetachedFromWindow() {
960 super.onDetachedFromWindow();
961
962 mBlink = false;
963 mBlinkState = true;
964
965 mHandler.removeMessages(MESSAGE_BLINK);
966 }
967
968 @Override
969 protected void dispatchDraw(Canvas canvas) {
970 if (mBlinkState) {
971 super.dispatchDraw(canvas);
972 }
973 }
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975}