blob: a17ed9d1ad0d88d5d4b9de30f31da5353033efad [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
Gilles Debunne30301932010-06-16 18:32:00 -070019import org.xmlpull.v1.XmlPullParser;
20import org.xmlpull.v1.XmlPullParserException;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.Context;
23import android.content.res.TypedArray;
24import android.content.res.XmlResourceParser;
25import android.util.AttributeSet;
26import android.util.Xml;
27
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import java.io.IOException;
29import java.lang.reflect.Constructor;
30import java.util.HashMap;
31
32/**
33 * This class is used to instantiate layout XML file into its corresponding View
34 * objects. It is never be used directly -- use
35 * {@link android.app.Activity#getLayoutInflater()} or
36 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
37 * that is already hooked up to the current context and correctly configured
38 * for the device you are running on. For example:
39 *
40 * <pre>LayoutInflater inflater = (LayoutInflater)context.getSystemService
41 * Context.LAYOUT_INFLATER_SERVICE);</pre>
42 *
43 * <p>
44 * To create a new LayoutInflater with an additional {@link Factory} for your
45 * own views, you can use {@link #cloneInContext} to clone an existing
46 * ViewFactory, and then call {@link #setFactory} on it to include your
47 * Factory.
48 *
49 * <p>
50 * For performance reasons, view inflation relies heavily on pre-processing of
51 * XML files that is done at build time. Therefore, it is not currently possible
52 * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
53 * it only works with an XmlPullParser returned from a compiled resource
54 * (R.<em>something</em> file.)
55 *
56 * @see Context#getSystemService
57 */
58public abstract class LayoutInflater {
59 private final boolean DEBUG = false;
60
61 /**
62 * This field should be made private, so it is hidden from the SDK.
63 * {@hide}
64 */
65 protected final Context mContext;
66
67 // these are optional, set by the caller
68 private boolean mFactorySet;
69 private Factory mFactory;
Dianne Hackborn625ac272010-09-17 18:29:22 -070070 private Factory2 mFactory2;
Dianne Hackborn420829e2011-01-28 11:30:35 -080071 private Factory2 mPrivateFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private Filter mFilter;
73
74 private final Object[] mConstructorArgs = new Object[2];
75
Gilles Debunne30301932010-06-16 18:32:00 -070076 private static final Class<?>[] mConstructorSignature = new Class[] {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 Context.class, AttributeSet.class};
78
Gilles Debunne30301932010-06-16 18:32:00 -070079 private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
80 new HashMap<String, Constructor<? extends View>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
82 private HashMap<String, Boolean> mFilterMap;
83
84 private static final String TAG_MERGE = "merge";
85 private static final String TAG_INCLUDE = "include";
86 private static final String TAG_REQUEST_FOCUS = "requestFocus";
87
88 /**
89 * Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed
90 * to be inflated.
91 *
92 */
93 public interface Filter {
94 /**
95 * Hook to allow clients of the LayoutInflater to restrict the set of Views
96 * that are allowed to be inflated.
97 *
98 * @param clazz The class object for the View that is about to be inflated
99 *
100 * @return True if this class is allowed to be inflated, or false otherwise
101 */
Gilles Debunnee6ac8b92010-06-17 10:55:04 -0700102 @SuppressWarnings("unchecked")
103 boolean onLoadClass(Class clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 }
105
106 public interface Factory {
107 /**
108 * Hook you can supply that is called when inflating from a LayoutInflater.
109 * You can use this to customize the tag names available in your XML
110 * layout files.
111 *
112 * <p>
113 * Note that it is good practice to prefix these custom names with your
114 * package (i.e., com.coolcompany.apps) to avoid conflicts with system
115 * names.
116 *
117 * @param name Tag name to be inflated.
118 * @param context The context the view is being created in.
119 * @param attrs Inflation attributes as specified in XML file.
120 *
121 * @return View Newly created view. Return null for the default
122 * behavior.
123 */
124 public View onCreateView(String name, Context context, AttributeSet attrs);
125 }
126
Dianne Hackborn625ac272010-09-17 18:29:22 -0700127 public interface Factory2 extends Factory {
128 /**
129 * Version of {@link #onCreateView(String, Context, AttributeSet)}
130 * that also supplies the parent that the view created view will be
131 * placed in.
132 *
133 * @param parent The parent that the created view will be placed
134 * in; <em>note that this may be null</em>.
135 * @param name Tag name to be inflated.
136 * @param context The context the view is being created in.
137 * @param attrs Inflation attributes as specified in XML file.
138 *
139 * @return View Newly created view. Return null for the default
140 * behavior.
141 */
142 public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
143 }
144
145 private static class FactoryMerger implements Factory2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146 private final Factory mF1, mF2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700147 private final Factory2 mF12, mF22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Dianne Hackborn625ac272010-09-17 18:29:22 -0700149 FactoryMerger(Factory f1, Factory2 f12, Factory f2, Factory2 f22) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 mF1 = f1;
151 mF2 = f2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700152 mF12 = f12;
153 mF22 = f22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 }
155
156 public View onCreateView(String name, Context context, AttributeSet attrs) {
157 View v = mF1.onCreateView(name, context, attrs);
158 if (v != null) return v;
159 return mF2.onCreateView(name, context, attrs);
160 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700161
162 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
163 View v = mF12 != null ? mF12.onCreateView(parent, name, context, attrs)
164 : mF1.onCreateView(name, context, attrs);
165 if (v != null) return v;
166 return mF22 != null ? mF22.onCreateView(parent, name, context, attrs)
167 : mF2.onCreateView(name, context, attrs);
168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 }
170
171 /**
172 * Create a new LayoutInflater instance associated with a particular Context.
173 * Applications will almost always want to use
174 * {@link Context#getSystemService Context.getSystemService()} to retrieve
175 * the standard {@link Context#LAYOUT_INFLATER_SERVICE Context.INFLATER_SERVICE}.
176 *
177 * @param context The Context in which this LayoutInflater will create its
178 * Views; most importantly, this supplies the theme from which the default
179 * values for their attributes are retrieved.
180 */
181 protected LayoutInflater(Context context) {
182 mContext = context;
183 }
184
185 /**
186 * Create a new LayoutInflater instance that is a copy of an existing
187 * LayoutInflater, optionally with its Context changed. For use in
188 * implementing {@link #cloneInContext}.
189 *
190 * @param original The original LayoutInflater to copy.
191 * @param newContext The new Context to use.
192 */
193 protected LayoutInflater(LayoutInflater original, Context newContext) {
194 mContext = newContext;
195 mFactory = original.mFactory;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700196 mFactory2 = original.mFactory2;
Dianne Hackborn420829e2011-01-28 11:30:35 -0800197 mPrivateFactory = original.mPrivateFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 mFilter = original.mFilter;
199 }
200
201 /**
202 * Obtains the LayoutInflater from the given context.
203 */
204 public static LayoutInflater from(Context context) {
205 LayoutInflater LayoutInflater =
206 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
207 if (LayoutInflater == null) {
208 throw new AssertionError("LayoutInflater not found.");
209 }
210 return LayoutInflater;
211 }
212
213 /**
214 * Create a copy of the existing LayoutInflater object, with the copy
215 * pointing to a different Context than the original. This is used by
216 * {@link ContextThemeWrapper} to create a new LayoutInflater to go along
217 * with the new Context theme.
218 *
219 * @param newContext The new Context to associate with the new LayoutInflater.
220 * May be the same as the original Context if desired.
221 *
222 * @return Returns a brand spanking new LayoutInflater object associated with
223 * the given Context.
224 */
225 public abstract LayoutInflater cloneInContext(Context newContext);
226
227 /**
228 * Return the context we are running in, for access to resources, class
229 * loader, etc.
230 */
231 public Context getContext() {
232 return mContext;
233 }
234
235 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700236 * Return the current {@link Factory} (or null). This is called on each element
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 * name. If the factory returns a View, add that to the hierarchy. If it
238 * returns null, proceed to call onCreateView(name).
239 */
240 public final Factory getFactory() {
241 return mFactory;
242 }
243
244 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700245 * Return the current {@link Factory2}. Returns null if no factory is set
246 * or the set factory does not implement the {@link Factory2} interface.
247 * This is called on each element
248 * name. If the factory returns a View, add that to the hierarchy. If it
249 * returns null, proceed to call onCreateView(name).
250 */
251 public final Factory2 getFactory2() {
252 return mFactory2;
253 }
254
255 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 * Attach a custom Factory interface for creating views while using
257 * this LayoutInflater. This must not be null, and can only be set once;
258 * after setting, you can not change the factory. This is
259 * called on each element name as the xml is parsed. If the factory returns
260 * a View, that is added to the hierarchy. If it returns null, the next
261 * factory default {@link #onCreateView} method is called.
262 *
263 * <p>If you have an existing
264 * LayoutInflater and want to add your own factory to it, use
265 * {@link #cloneInContext} to clone the existing instance and then you
266 * can use this function (once) on the returned new instance. This will
267 * merge your own factory with whatever factory the original instance is
268 * using.
269 */
270 public void setFactory(Factory factory) {
271 if (mFactorySet) {
272 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
273 }
274 if (factory == null) {
275 throw new NullPointerException("Given factory can not be null");
276 }
277 mFactorySet = true;
278 if (mFactory == null) {
279 mFactory = factory;
280 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700281 mFactory = new FactoryMerger(factory, null, mFactory, mFactory2);
282 }
283 }
284
285 /**
286 * Like {@link #setFactory}, but allows you to set a {@link Factory2}
287 * interface.
288 */
289 public void setFactory2(Factory2 factory) {
290 if (mFactorySet) {
291 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
292 }
293 if (factory == null) {
294 throw new NullPointerException("Given factory can not be null");
295 }
296 mFactorySet = true;
297 if (mFactory == null) {
298 mFactory = mFactory2 = factory;
299 } else {
300 mFactory = new FactoryMerger(factory, factory, mFactory, mFactory2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302 }
303
304 /**
Dianne Hackborn420829e2011-01-28 11:30:35 -0800305 * @hide for use by framework
306 */
307 public void setPrivateFactory(Factory2 factory) {
308 mPrivateFactory = factory;
309 }
310
311 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 * @return The {@link Filter} currently used by this LayoutInflater to restrict the set of Views
313 * that are allowed to be inflated.
314 */
315 public Filter getFilter() {
316 return mFilter;
317 }
318
319 /**
320 * Sets the {@link Filter} to by this LayoutInflater. If a view is attempted to be inflated
321 * which is not allowed by the {@link Filter}, the {@link #inflate(int, ViewGroup)} call will
322 * throw an {@link InflateException}. This filter will replace any previous filter set on this
323 * LayoutInflater.
324 *
325 * @param filter The Filter which restricts the set of Views that are allowed to be inflated.
326 * This filter will replace any previous filter set on this LayoutInflater.
327 */
328 public void setFilter(Filter filter) {
329 mFilter = filter;
330 if (filter != null) {
331 mFilterMap = new HashMap<String, Boolean>();
332 }
333 }
334
335 /**
336 * Inflate a new view hierarchy from the specified xml resource. Throws
337 * {@link InflateException} if there is an error.
338 *
339 * @param resource ID for an XML layout resource to load (e.g.,
340 * <code>R.layout.main_page</code>)
341 * @param root Optional view to be the parent of the generated hierarchy.
342 * @return The root View of the inflated hierarchy. If root was supplied,
343 * this is the root View; otherwise it is the root of the inflated
344 * XML file.
345 */
346 public View inflate(int resource, ViewGroup root) {
347 return inflate(resource, root, root != null);
348 }
349
350 /**
351 * Inflate a new view hierarchy from the specified xml node. Throws
352 * {@link InflateException} if there is an error. *
353 * <p>
354 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
355 * reasons, view inflation relies heavily on pre-processing of XML files
356 * that is done at build time. Therefore, it is not currently possible to
357 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
358 *
359 * @param parser XML dom node containing the description of the view
360 * hierarchy.
361 * @param root Optional view to be the parent of the generated hierarchy.
362 * @return The root View of the inflated hierarchy. If root was supplied,
363 * this is the root View; otherwise it is the root of the inflated
364 * XML file.
365 */
366 public View inflate(XmlPullParser parser, ViewGroup root) {
367 return inflate(parser, root, root != null);
368 }
369
370 /**
371 * Inflate a new view hierarchy from the specified xml resource. Throws
372 * {@link InflateException} if there is an error.
373 *
374 * @param resource ID for an XML layout resource to load (e.g.,
375 * <code>R.layout.main_page</code>)
376 * @param root Optional view to be the parent of the generated hierarchy (if
377 * <em>attachToRoot</em> is true), or else simply an object that
378 * provides a set of LayoutParams values for root of the returned
379 * hierarchy (if <em>attachToRoot</em> is false.)
380 * @param attachToRoot Whether the inflated hierarchy should be attached to
381 * the root parameter? If false, root is only used to create the
382 * correct subclass of LayoutParams for the root view in the XML.
383 * @return The root View of the inflated hierarchy. If root was supplied and
384 * attachToRoot is true, this is root; otherwise it is the root of
385 * the inflated XML file.
386 */
387 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
388 if (DEBUG) System.out.println("INFLATING from resource: " + resource);
389 XmlResourceParser parser = getContext().getResources().getLayout(resource);
390 try {
391 return inflate(parser, root, attachToRoot);
392 } finally {
393 parser.close();
394 }
395 }
396
397 /**
398 * Inflate a new view hierarchy from the specified XML node. Throws
399 * {@link InflateException} if there is an error.
400 * <p>
401 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
402 * reasons, view inflation relies heavily on pre-processing of XML files
403 * that is done at build time. Therefore, it is not currently possible to
404 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
405 *
406 * @param parser XML dom node containing the description of the view
407 * hierarchy.
408 * @param root Optional view to be the parent of the generated hierarchy (if
409 * <em>attachToRoot</em> is true), or else simply an object that
410 * provides a set of LayoutParams values for root of the returned
411 * hierarchy (if <em>attachToRoot</em> is false.)
412 * @param attachToRoot Whether the inflated hierarchy should be attached to
413 * the root parameter? If false, root is only used to create the
414 * correct subclass of LayoutParams for the root view in the XML.
415 * @return The root View of the inflated hierarchy. If root was supplied and
416 * attachToRoot is true, this is root; otherwise it is the root of
417 * the inflated XML file.
418 */
419 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
420 synchronized (mConstructorArgs) {
421 final AttributeSet attrs = Xml.asAttributeSet(parser);
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700422 Context lastContext = (Context)mConstructorArgs[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 mConstructorArgs[0] = mContext;
424 View result = root;
425
426 try {
427 // Look for the root node.
428 int type;
429 while ((type = parser.next()) != XmlPullParser.START_TAG &&
430 type != XmlPullParser.END_DOCUMENT) {
431 // Empty
432 }
433
434 if (type != XmlPullParser.START_TAG) {
435 throw new InflateException(parser.getPositionDescription()
436 + ": No start tag found!");
437 }
438
439 final String name = parser.getName();
440
441 if (DEBUG) {
442 System.out.println("**************************");
443 System.out.println("Creating root view: "
444 + name);
445 System.out.println("**************************");
446 }
447
448 if (TAG_MERGE.equals(name)) {
449 if (root == null || !attachToRoot) {
450 throw new InflateException("<merge /> can be used only with a valid "
451 + "ViewGroup root and attachToRoot=true");
452 }
453
Romain Guy9295ada2010-06-15 11:33:24 -0700454 rInflate(parser, root, attrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 } else {
456 // Temp is the root view that was found in the xml
Dianne Hackborn625ac272010-09-17 18:29:22 -0700457 View temp = createViewFromTag(root, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458
459 ViewGroup.LayoutParams params = null;
460
461 if (root != null) {
462 if (DEBUG) {
463 System.out.println("Creating params from root: " +
464 root);
465 }
466 // Create layout params that match root, if supplied
467 params = root.generateLayoutParams(attrs);
468 if (!attachToRoot) {
469 // Set the layout params for temp if we are not
470 // attaching. (If we are, we use addView, below)
471 temp.setLayoutParams(params);
472 }
473 }
474
475 if (DEBUG) {
476 System.out.println("-----> start inflating children");
477 }
478 // Inflate all children under temp
Romain Guy9295ada2010-06-15 11:33:24 -0700479 rInflate(parser, temp, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 if (DEBUG) {
481 System.out.println("-----> done inflating children");
482 }
483
484 // We are supposed to attach all the views we found (int temp)
485 // to root. Do that now.
486 if (root != null && attachToRoot) {
487 root.addView(temp, params);
488 }
489
490 // Decide whether to return the root that was passed in or the
491 // top view found in xml.
492 if (root == null || !attachToRoot) {
493 result = temp;
494 }
495 }
496
497 } catch (XmlPullParserException e) {
498 InflateException ex = new InflateException(e.getMessage());
499 ex.initCause(e);
500 throw ex;
501 } catch (IOException e) {
502 InflateException ex = new InflateException(
503 parser.getPositionDescription()
504 + ": " + e.getMessage());
505 ex.initCause(e);
506 throw ex;
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700507 } finally {
508 // Don't retain static reference on context.
509 mConstructorArgs[0] = lastContext;
510 mConstructorArgs[1] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 }
512
513 return result;
514 }
515 }
516
517 /**
518 * Low-level function for instantiating a view by name. This attempts to
519 * instantiate a view class of the given <var>name</var> found in this
520 * LayoutInflater's ClassLoader.
521 *
522 * <p>
523 * There are two things that can happen in an error case: either the
524 * exception describing the error will be thrown, or a null will be
525 * returned. You must deal with both possibilities -- the former will happen
526 * the first time createView() is called for a class of a particular name,
527 * the latter every time there-after for that class name.
528 *
529 * @param name The full name of the class to be instantiated.
530 * @param attrs The XML attributes supplied for this instance.
531 *
Gilles Debunne30301932010-06-16 18:32:00 -0700532 * @return View The newly instantiated view, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 */
534 public final View createView(String name, String prefix, AttributeSet attrs)
535 throws ClassNotFoundException, InflateException {
Gilles Debunne30301932010-06-16 18:32:00 -0700536 Constructor<? extends View> constructor = sConstructorMap.get(name);
537 Class<? extends View> clazz = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538
539 try {
540 if (constructor == null) {
541 // Class not found in the cache, see if it's real, and try to add it
Romain Guyd03b8802009-09-16 14:36:16 -0700542 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700543 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544
545 if (mFilter != null && clazz != null) {
546 boolean allowed = mFilter.onLoadClass(clazz);
547 if (!allowed) {
548 failNotAllowed(name, prefix, attrs);
549 }
550 }
551 constructor = clazz.getConstructor(mConstructorSignature);
552 sConstructorMap.put(name, constructor);
553 } else {
554 // If we have a filter, apply it to cached constructor
555 if (mFilter != null) {
556 // Have we seen this name before?
557 Boolean allowedState = mFilterMap.get(name);
558 if (allowedState == null) {
559 // New class -- remember whether it is allowed
Romain Guyd03b8802009-09-16 14:36:16 -0700560 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700561 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562
563 boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
564 mFilterMap.put(name, allowed);
565 if (!allowed) {
566 failNotAllowed(name, prefix, attrs);
567 }
568 } else if (allowedState.equals(Boolean.FALSE)) {
569 failNotAllowed(name, prefix, attrs);
570 }
571 }
572 }
573
574 Object[] args = mConstructorArgs;
575 args[1] = attrs;
Gilles Debunne30301932010-06-16 18:32:00 -0700576 return constructor.newInstance(args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577
578 } catch (NoSuchMethodException e) {
579 InflateException ie = new InflateException(attrs.getPositionDescription()
580 + ": Error inflating class "
581 + (prefix != null ? (prefix + name) : name));
582 ie.initCause(e);
583 throw ie;
584
Gilles Debunne30301932010-06-16 18:32:00 -0700585 } catch (ClassCastException e) {
586 // If loaded class is not a View subclass
587 InflateException ie = new InflateException(attrs.getPositionDescription()
588 + ": Class is not a View "
589 + (prefix != null ? (prefix + name) : name));
590 ie.initCause(e);
591 throw ie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 } catch (ClassNotFoundException e) {
593 // If loadClass fails, we should propagate the exception.
594 throw e;
595 } catch (Exception e) {
596 InflateException ie = new InflateException(attrs.getPositionDescription()
597 + ": Error inflating class "
Romain Guyd03b8802009-09-16 14:36:16 -0700598 + (clazz == null ? "<unknown>" : clazz.getName()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 ie.initCause(e);
600 throw ie;
601 }
602 }
603
604 /**
Gilles Debunne30301932010-06-16 18:32:00 -0700605 * Throw an exception because the specified class is not allowed to be inflated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 */
607 private void failNotAllowed(String name, String prefix, AttributeSet attrs) {
608 InflateException ie = new InflateException(attrs.getPositionDescription()
609 + ": Class not allowed to be inflated "
610 + (prefix != null ? (prefix + name) : name));
611 throw ie;
612 }
613
614 /**
615 * This routine is responsible for creating the correct subclass of View
616 * given the xml element name. Override it to handle custom view objects. If
617 * you override this in your subclass be sure to call through to
618 * super.onCreateView(name) for names you do not recognize.
619 *
620 * @param name The fully qualified class name of the View to be create.
621 * @param attrs An AttributeSet of attributes to apply to the View.
622 *
623 * @return View The View created.
624 */
625 protected View onCreateView(String name, AttributeSet attrs)
626 throws ClassNotFoundException {
627 return createView(name, "android.view.", attrs);
628 }
629
Dianne Hackborn625ac272010-09-17 18:29:22 -0700630 /**
631 * Version of {@link #onCreateView(String, AttributeSet)} that also
632 * takes the future parent of the view being constructure. The default
633 * implementation simply calls {@link #onCreateView(String, AttributeSet)}.
634 *
635 * @param parent The future parent of the returned view. <em>Note that
636 * this may be null.</em>
637 * @param name The fully qualified class name of the View to be create.
638 * @param attrs An AttributeSet of attributes to apply to the View.
639 *
640 * @return View The View created.
641 */
642 protected View onCreateView(View parent, String name, AttributeSet attrs)
643 throws ClassNotFoundException {
644 return onCreateView(name, attrs);
645 }
646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 /*
648 * default visibility so the BridgeInflater can override it.
649 */
Dianne Hackborn625ac272010-09-17 18:29:22 -0700650 View createViewFromTag(View parent, String name, AttributeSet attrs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 if (name.equals("view")) {
652 name = attrs.getAttributeValue(null, "class");
653 }
654
655 if (DEBUG) System.out.println("******** Creating view: " + name);
656
657 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700658 View view;
659 if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
660 else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
661 else view = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662
Dianne Hackborn420829e2011-01-28 11:30:35 -0800663 if (view == null && mPrivateFactory != null) {
664 view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
665 }
666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 if (view == null) {
668 if (-1 == name.indexOf('.')) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700669 view = onCreateView(parent, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 } else {
671 view = createView(name, null, attrs);
672 }
673 }
674
675 if (DEBUG) System.out.println("Created view is: " + view);
676 return view;
677
678 } catch (InflateException e) {
679 throw e;
680
681 } catch (ClassNotFoundException e) {
682 InflateException ie = new InflateException(attrs.getPositionDescription()
683 + ": Error inflating class " + name);
684 ie.initCause(e);
685 throw ie;
686
687 } catch (Exception e) {
688 InflateException ie = new InflateException(attrs.getPositionDescription()
689 + ": Error inflating class " + name);
690 ie.initCause(e);
691 throw ie;
692 }
693 }
694
695 /**
696 * Recursive method used to descend down the xml hierarchy and instantiate
697 * views, instantiate their children, and then call onFinishInflate().
698 */
Romain Guy9295ada2010-06-15 11:33:24 -0700699 private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
700 boolean finishInflate) throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 final int depth = parser.getDepth();
703 int type;
704
705 while (((type = parser.next()) != XmlPullParser.END_TAG ||
706 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
707
708 if (type != XmlPullParser.START_TAG) {
709 continue;
710 }
711
712 final String name = parser.getName();
713
714 if (TAG_REQUEST_FOCUS.equals(name)) {
715 parseRequestFocus(parser, parent);
716 } else if (TAG_INCLUDE.equals(name)) {
717 if (parser.getDepth() == 0) {
718 throw new InflateException("<include /> cannot be the root element");
719 }
720 parseInclude(parser, parent, attrs);
721 } else if (TAG_MERGE.equals(name)) {
722 throw new InflateException("<merge /> must be the root element");
723 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700724 final View view = createViewFromTag(parent, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 final ViewGroup viewGroup = (ViewGroup) parent;
726 final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
Romain Guy9295ada2010-06-15 11:33:24 -0700727 rInflate(parser, view, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 viewGroup.addView(view, params);
729 }
730 }
731
Romain Guy9295ada2010-06-15 11:33:24 -0700732 if (finishInflate) parent.onFinishInflate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734
735 private void parseRequestFocus(XmlPullParser parser, View parent)
736 throws XmlPullParserException, IOException {
737 int type;
738 parent.requestFocus();
739 final int currentDepth = parser.getDepth();
740 while (((type = parser.next()) != XmlPullParser.END_TAG ||
741 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
742 // Empty
743 }
744 }
745
746 private void parseInclude(XmlPullParser parser, View parent, AttributeSet attrs)
747 throws XmlPullParserException, IOException {
748
749 int type;
750
751 if (parent instanceof ViewGroup) {
752 final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
753 if (layout == 0) {
754 final String value = attrs.getAttributeValue(null, "layout");
755 if (value == null) {
756 throw new InflateException("You must specifiy a layout in the"
757 + " include tag: <include layout=\"@layout/layoutID\" />");
758 } else {
759 throw new InflateException("You must specifiy a valid layout "
760 + "reference. The layout ID " + value + " is not valid.");
761 }
762 } else {
763 final XmlResourceParser childParser =
764 getContext().getResources().getLayout(layout);
765
766 try {
767 final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
768
769 while ((type = childParser.next()) != XmlPullParser.START_TAG &&
770 type != XmlPullParser.END_DOCUMENT) {
771 // Empty.
772 }
773
774 if (type != XmlPullParser.START_TAG) {
775 throw new InflateException(childParser.getPositionDescription() +
776 ": No start tag found!");
777 }
778
779 final String childName = childParser.getName();
780
781 if (TAG_MERGE.equals(childName)) {
782 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700783 rInflate(childParser, parent, childAttrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700785 final View view = createViewFromTag(parent, childName, childAttrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 final ViewGroup group = (ViewGroup) parent;
787
788 // We try to load the layout params set in the <include /> tag. If
789 // they don't exist, we will rely on the layout params set in the
790 // included XML file.
791 // During a layoutparams generation, a runtime exception is thrown
792 // if either layout_width or layout_height is missing. We catch
793 // this exception and set localParams accordingly: true means we
794 // successfully loaded layout params from the <include /> tag,
795 // false means we need to rely on the included layout params.
796 ViewGroup.LayoutParams params = null;
797 try {
798 params = group.generateLayoutParams(attrs);
799 } catch (RuntimeException e) {
800 params = group.generateLayoutParams(childAttrs);
801 } finally {
802 if (params != null) {
803 view.setLayoutParams(params);
804 }
805 }
806
807 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700808 rInflate(childParser, view, childAttrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
810 // Attempt to override the included layout's android:id with the
811 // one set on the <include /> tag itself.
812 TypedArray a = mContext.obtainStyledAttributes(attrs,
813 com.android.internal.R.styleable.View, 0, 0);
814 int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
815 // While we're at it, let's try to override android:visibility.
816 int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
817 a.recycle();
818
819 if (id != View.NO_ID) {
820 view.setId(id);
821 }
822
823 switch (visibility) {
824 case 0:
825 view.setVisibility(View.VISIBLE);
826 break;
827 case 1:
828 view.setVisibility(View.INVISIBLE);
829 break;
830 case 2:
831 view.setVisibility(View.GONE);
832 break;
833 }
834
835 group.addView(view);
836 }
837 } finally {
838 childParser.close();
839 }
840 }
841 } else {
842 throw new InflateException("<include /> can only be used inside of a ViewGroup");
843 }
844
845 final int currentDepth = parser.getDepth();
846 while (((type = parser.next()) != XmlPullParser.END_TAG ||
847 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
848 // Empty
849 }
850 }
851}