blob: 3e3dbdf32c34f41853be87e37b48e23170488063 [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;
70 private Filter mFilter;
71
72 private final Object[] mConstructorArgs = new Object[2];
73
Gilles Debunne30301932010-06-16 18:32:00 -070074 private static final Class<?>[] mConstructorSignature = new Class[] {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 Context.class, AttributeSet.class};
76
Gilles Debunne30301932010-06-16 18:32:00 -070077 private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
78 new HashMap<String, Constructor<? extends View>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
80 private HashMap<String, Boolean> mFilterMap;
81
82 private static final String TAG_MERGE = "merge";
83 private static final String TAG_INCLUDE = "include";
84 private static final String TAG_REQUEST_FOCUS = "requestFocus";
85
86 /**
87 * Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed
88 * to be inflated.
89 *
90 */
91 public interface Filter {
92 /**
93 * Hook to allow clients of the LayoutInflater to restrict the set of Views
94 * that are allowed to be inflated.
95 *
96 * @param clazz The class object for the View that is about to be inflated
97 *
98 * @return True if this class is allowed to be inflated, or false otherwise
99 */
Gilles Debunne30301932010-06-16 18:32:00 -0700100 boolean onLoadClass(Class<?> clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 }
102
103 public interface Factory {
104 /**
105 * Hook you can supply that is called when inflating from a LayoutInflater.
106 * You can use this to customize the tag names available in your XML
107 * layout files.
108 *
109 * <p>
110 * Note that it is good practice to prefix these custom names with your
111 * package (i.e., com.coolcompany.apps) to avoid conflicts with system
112 * names.
113 *
114 * @param name Tag name to be inflated.
115 * @param context The context the view is being created in.
116 * @param attrs Inflation attributes as specified in XML file.
117 *
118 * @return View Newly created view. Return null for the default
119 * behavior.
120 */
121 public View onCreateView(String name, Context context, AttributeSet attrs);
122 }
123
124 private static class FactoryMerger implements Factory {
125 private final Factory mF1, mF2;
126
127 FactoryMerger(Factory f1, Factory f2) {
128 mF1 = f1;
129 mF2 = f2;
130 }
131
132 public View onCreateView(String name, Context context, AttributeSet attrs) {
133 View v = mF1.onCreateView(name, context, attrs);
134 if (v != null) return v;
135 return mF2.onCreateView(name, context, attrs);
136 }
137 }
138
139 /**
140 * Create a new LayoutInflater instance associated with a particular Context.
141 * Applications will almost always want to use
142 * {@link Context#getSystemService Context.getSystemService()} to retrieve
143 * the standard {@link Context#LAYOUT_INFLATER_SERVICE Context.INFLATER_SERVICE}.
144 *
145 * @param context The Context in which this LayoutInflater will create its
146 * Views; most importantly, this supplies the theme from which the default
147 * values for their attributes are retrieved.
148 */
149 protected LayoutInflater(Context context) {
150 mContext = context;
151 }
152
153 /**
154 * Create a new LayoutInflater instance that is a copy of an existing
155 * LayoutInflater, optionally with its Context changed. For use in
156 * implementing {@link #cloneInContext}.
157 *
158 * @param original The original LayoutInflater to copy.
159 * @param newContext The new Context to use.
160 */
161 protected LayoutInflater(LayoutInflater original, Context newContext) {
162 mContext = newContext;
163 mFactory = original.mFactory;
164 mFilter = original.mFilter;
165 }
166
167 /**
168 * Obtains the LayoutInflater from the given context.
169 */
170 public static LayoutInflater from(Context context) {
171 LayoutInflater LayoutInflater =
172 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
173 if (LayoutInflater == null) {
174 throw new AssertionError("LayoutInflater not found.");
175 }
176 return LayoutInflater;
177 }
178
179 /**
180 * Create a copy of the existing LayoutInflater object, with the copy
181 * pointing to a different Context than the original. This is used by
182 * {@link ContextThemeWrapper} to create a new LayoutInflater to go along
183 * with the new Context theme.
184 *
185 * @param newContext The new Context to associate with the new LayoutInflater.
186 * May be the same as the original Context if desired.
187 *
188 * @return Returns a brand spanking new LayoutInflater object associated with
189 * the given Context.
190 */
191 public abstract LayoutInflater cloneInContext(Context newContext);
192
193 /**
194 * Return the context we are running in, for access to resources, class
195 * loader, etc.
196 */
197 public Context getContext() {
198 return mContext;
199 }
200
201 /**
202 * Return the current factory (or null). This is called on each element
203 * name. If the factory returns a View, add that to the hierarchy. If it
204 * returns null, proceed to call onCreateView(name).
205 */
206 public final Factory getFactory() {
207 return mFactory;
208 }
209
210 /**
211 * Attach a custom Factory interface for creating views while using
212 * this LayoutInflater. This must not be null, and can only be set once;
213 * after setting, you can not change the factory. This is
214 * called on each element name as the xml is parsed. If the factory returns
215 * a View, that is added to the hierarchy. If it returns null, the next
216 * factory default {@link #onCreateView} method is called.
217 *
218 * <p>If you have an existing
219 * LayoutInflater and want to add your own factory to it, use
220 * {@link #cloneInContext} to clone the existing instance and then you
221 * can use this function (once) on the returned new instance. This will
222 * merge your own factory with whatever factory the original instance is
223 * using.
224 */
225 public void setFactory(Factory factory) {
226 if (mFactorySet) {
227 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
228 }
229 if (factory == null) {
230 throw new NullPointerException("Given factory can not be null");
231 }
232 mFactorySet = true;
233 if (mFactory == null) {
234 mFactory = factory;
235 } else {
236 mFactory = new FactoryMerger(factory, mFactory);
237 }
238 }
239
240 /**
241 * @return The {@link Filter} currently used by this LayoutInflater to restrict the set of Views
242 * that are allowed to be inflated.
243 */
244 public Filter getFilter() {
245 return mFilter;
246 }
247
248 /**
249 * Sets the {@link Filter} to by this LayoutInflater. If a view is attempted to be inflated
250 * which is not allowed by the {@link Filter}, the {@link #inflate(int, ViewGroup)} call will
251 * throw an {@link InflateException}. This filter will replace any previous filter set on this
252 * LayoutInflater.
253 *
254 * @param filter The Filter which restricts the set of Views that are allowed to be inflated.
255 * This filter will replace any previous filter set on this LayoutInflater.
256 */
257 public void setFilter(Filter filter) {
258 mFilter = filter;
259 if (filter != null) {
260 mFilterMap = new HashMap<String, Boolean>();
261 }
262 }
263
264 /**
265 * Inflate a new view hierarchy from the specified xml resource. Throws
266 * {@link InflateException} if there is an error.
267 *
268 * @param resource ID for an XML layout resource to load (e.g.,
269 * <code>R.layout.main_page</code>)
270 * @param root Optional view to be the parent of the generated hierarchy.
271 * @return The root View of the inflated hierarchy. If root was supplied,
272 * this is the root View; otherwise it is the root of the inflated
273 * XML file.
274 */
275 public View inflate(int resource, ViewGroup root) {
276 return inflate(resource, root, root != null);
277 }
278
279 /**
280 * Inflate a new view hierarchy from the specified xml node. Throws
281 * {@link InflateException} if there is an error. *
282 * <p>
283 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
284 * reasons, view inflation relies heavily on pre-processing of XML files
285 * that is done at build time. Therefore, it is not currently possible to
286 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
287 *
288 * @param parser XML dom node containing the description of the view
289 * hierarchy.
290 * @param root Optional view to be the parent of the generated hierarchy.
291 * @return The root View of the inflated hierarchy. If root was supplied,
292 * this is the root View; otherwise it is the root of the inflated
293 * XML file.
294 */
295 public View inflate(XmlPullParser parser, ViewGroup root) {
296 return inflate(parser, root, root != null);
297 }
298
299 /**
300 * Inflate a new view hierarchy from the specified xml resource. Throws
301 * {@link InflateException} if there is an error.
302 *
303 * @param resource ID for an XML layout resource to load (e.g.,
304 * <code>R.layout.main_page</code>)
305 * @param root Optional view to be the parent of the generated hierarchy (if
306 * <em>attachToRoot</em> is true), or else simply an object that
307 * provides a set of LayoutParams values for root of the returned
308 * hierarchy (if <em>attachToRoot</em> is false.)
309 * @param attachToRoot Whether the inflated hierarchy should be attached to
310 * the root parameter? If false, root is only used to create the
311 * correct subclass of LayoutParams for the root view in the XML.
312 * @return The root View of the inflated hierarchy. If root was supplied and
313 * attachToRoot is true, this is root; otherwise it is the root of
314 * the inflated XML file.
315 */
316 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
317 if (DEBUG) System.out.println("INFLATING from resource: " + resource);
318 XmlResourceParser parser = getContext().getResources().getLayout(resource);
319 try {
320 return inflate(parser, root, attachToRoot);
321 } finally {
322 parser.close();
323 }
324 }
325
326 /**
327 * Inflate a new view hierarchy from the specified XML node. Throws
328 * {@link InflateException} if there is an error.
329 * <p>
330 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
331 * reasons, view inflation relies heavily on pre-processing of XML files
332 * that is done at build time. Therefore, it is not currently possible to
333 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
334 *
335 * @param parser XML dom node containing the description of the view
336 * hierarchy.
337 * @param root Optional view to be the parent of the generated hierarchy (if
338 * <em>attachToRoot</em> is true), or else simply an object that
339 * provides a set of LayoutParams values for root of the returned
340 * hierarchy (if <em>attachToRoot</em> is false.)
341 * @param attachToRoot Whether the inflated hierarchy should be attached to
342 * the root parameter? If false, root is only used to create the
343 * correct subclass of LayoutParams for the root view in the XML.
344 * @return The root View of the inflated hierarchy. If root was supplied and
345 * attachToRoot is true, this is root; otherwise it is the root of
346 * the inflated XML file.
347 */
348 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
349 synchronized (mConstructorArgs) {
350 final AttributeSet attrs = Xml.asAttributeSet(parser);
351 mConstructorArgs[0] = mContext;
352 View result = root;
353
354 try {
355 // Look for the root node.
356 int type;
357 while ((type = parser.next()) != XmlPullParser.START_TAG &&
358 type != XmlPullParser.END_DOCUMENT) {
359 // Empty
360 }
361
362 if (type != XmlPullParser.START_TAG) {
363 throw new InflateException(parser.getPositionDescription()
364 + ": No start tag found!");
365 }
366
367 final String name = parser.getName();
368
369 if (DEBUG) {
370 System.out.println("**************************");
371 System.out.println("Creating root view: "
372 + name);
373 System.out.println("**************************");
374 }
375
376 if (TAG_MERGE.equals(name)) {
377 if (root == null || !attachToRoot) {
378 throw new InflateException("<merge /> can be used only with a valid "
379 + "ViewGroup root and attachToRoot=true");
380 }
381
Romain Guy9295ada2010-06-15 11:33:24 -0700382 rInflate(parser, root, attrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 } else {
384 // Temp is the root view that was found in the xml
385 View temp = createViewFromTag(name, attrs);
386
387 ViewGroup.LayoutParams params = null;
388
389 if (root != null) {
390 if (DEBUG) {
391 System.out.println("Creating params from root: " +
392 root);
393 }
394 // Create layout params that match root, if supplied
395 params = root.generateLayoutParams(attrs);
396 if (!attachToRoot) {
397 // Set the layout params for temp if we are not
398 // attaching. (If we are, we use addView, below)
399 temp.setLayoutParams(params);
400 }
401 }
402
403 if (DEBUG) {
404 System.out.println("-----> start inflating children");
405 }
406 // Inflate all children under temp
Romain Guy9295ada2010-06-15 11:33:24 -0700407 rInflate(parser, temp, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 if (DEBUG) {
409 System.out.println("-----> done inflating children");
410 }
411
412 // We are supposed to attach all the views we found (int temp)
413 // to root. Do that now.
414 if (root != null && attachToRoot) {
415 root.addView(temp, params);
416 }
417
418 // Decide whether to return the root that was passed in or the
419 // top view found in xml.
420 if (root == null || !attachToRoot) {
421 result = temp;
422 }
423 }
424
425 } catch (XmlPullParserException e) {
426 InflateException ex = new InflateException(e.getMessage());
427 ex.initCause(e);
428 throw ex;
429 } catch (IOException e) {
430 InflateException ex = new InflateException(
431 parser.getPositionDescription()
432 + ": " + e.getMessage());
433 ex.initCause(e);
434 throw ex;
435 }
436
437 return result;
438 }
439 }
440
441 /**
442 * Low-level function for instantiating a view by name. This attempts to
443 * instantiate a view class of the given <var>name</var> found in this
444 * LayoutInflater's ClassLoader.
445 *
446 * <p>
447 * There are two things that can happen in an error case: either the
448 * exception describing the error will be thrown, or a null will be
449 * returned. You must deal with both possibilities -- the former will happen
450 * the first time createView() is called for a class of a particular name,
451 * the latter every time there-after for that class name.
452 *
453 * @param name The full name of the class to be instantiated.
454 * @param attrs The XML attributes supplied for this instance.
455 *
Gilles Debunne30301932010-06-16 18:32:00 -0700456 * @return View The newly instantiated view, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 */
458 public final View createView(String name, String prefix, AttributeSet attrs)
459 throws ClassNotFoundException, InflateException {
Gilles Debunne30301932010-06-16 18:32:00 -0700460 Constructor<? extends View> constructor = sConstructorMap.get(name);
461 Class<? extends View> clazz = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462
463 try {
464 if (constructor == null) {
465 // Class not found in the cache, see if it's real, and try to add it
Romain Guyd03b8802009-09-16 14:36:16 -0700466 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700467 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468
469 if (mFilter != null && clazz != null) {
470 boolean allowed = mFilter.onLoadClass(clazz);
471 if (!allowed) {
472 failNotAllowed(name, prefix, attrs);
473 }
474 }
475 constructor = clazz.getConstructor(mConstructorSignature);
476 sConstructorMap.put(name, constructor);
477 } else {
478 // If we have a filter, apply it to cached constructor
479 if (mFilter != null) {
480 // Have we seen this name before?
481 Boolean allowedState = mFilterMap.get(name);
482 if (allowedState == null) {
483 // New class -- remember whether it is allowed
Romain Guyd03b8802009-09-16 14:36:16 -0700484 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700485 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486
487 boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
488 mFilterMap.put(name, allowed);
489 if (!allowed) {
490 failNotAllowed(name, prefix, attrs);
491 }
492 } else if (allowedState.equals(Boolean.FALSE)) {
493 failNotAllowed(name, prefix, attrs);
494 }
495 }
496 }
497
498 Object[] args = mConstructorArgs;
499 args[1] = attrs;
Gilles Debunne30301932010-06-16 18:32:00 -0700500 return constructor.newInstance(args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501
502 } catch (NoSuchMethodException e) {
503 InflateException ie = new InflateException(attrs.getPositionDescription()
504 + ": Error inflating class "
505 + (prefix != null ? (prefix + name) : name));
506 ie.initCause(e);
507 throw ie;
508
Gilles Debunne30301932010-06-16 18:32:00 -0700509 } catch (ClassCastException e) {
510 // If loaded class is not a View subclass
511 InflateException ie = new InflateException(attrs.getPositionDescription()
512 + ": Class is not a View "
513 + (prefix != null ? (prefix + name) : name));
514 ie.initCause(e);
515 throw ie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 } catch (ClassNotFoundException e) {
517 // If loadClass fails, we should propagate the exception.
518 throw e;
519 } catch (Exception e) {
520 InflateException ie = new InflateException(attrs.getPositionDescription()
521 + ": Error inflating class "
Romain Guyd03b8802009-09-16 14:36:16 -0700522 + (clazz == null ? "<unknown>" : clazz.getName()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 ie.initCause(e);
524 throw ie;
525 }
526 }
527
528 /**
Gilles Debunne30301932010-06-16 18:32:00 -0700529 * Throw an exception because the specified class is not allowed to be inflated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 */
531 private void failNotAllowed(String name, String prefix, AttributeSet attrs) {
532 InflateException ie = new InflateException(attrs.getPositionDescription()
533 + ": Class not allowed to be inflated "
534 + (prefix != null ? (prefix + name) : name));
535 throw ie;
536 }
537
538 /**
539 * This routine is responsible for creating the correct subclass of View
540 * given the xml element name. Override it to handle custom view objects. If
541 * you override this in your subclass be sure to call through to
542 * super.onCreateView(name) for names you do not recognize.
543 *
544 * @param name The fully qualified class name of the View to be create.
545 * @param attrs An AttributeSet of attributes to apply to the View.
546 *
547 * @return View The View created.
548 */
549 protected View onCreateView(String name, AttributeSet attrs)
550 throws ClassNotFoundException {
551 return createView(name, "android.view.", attrs);
552 }
553
554 /*
555 * default visibility so the BridgeInflater can override it.
556 */
557 View createViewFromTag(String name, AttributeSet attrs) {
558 if (name.equals("view")) {
559 name = attrs.getAttributeValue(null, "class");
560 }
561
562 if (DEBUG) System.out.println("******** Creating view: " + name);
563
564 try {
565 View view = (mFactory == null) ? null : mFactory.onCreateView(name,
566 mContext, attrs);
567
568 if (view == null) {
569 if (-1 == name.indexOf('.')) {
570 view = onCreateView(name, attrs);
571 } else {
572 view = createView(name, null, attrs);
573 }
574 }
575
576 if (DEBUG) System.out.println("Created view is: " + view);
577 return view;
578
579 } catch (InflateException e) {
580 throw e;
581
582 } catch (ClassNotFoundException e) {
583 InflateException ie = new InflateException(attrs.getPositionDescription()
584 + ": Error inflating class " + name);
585 ie.initCause(e);
586 throw ie;
587
588 } catch (Exception e) {
589 InflateException ie = new InflateException(attrs.getPositionDescription()
590 + ": Error inflating class " + name);
591 ie.initCause(e);
592 throw ie;
593 }
594 }
595
596 /**
597 * Recursive method used to descend down the xml hierarchy and instantiate
598 * views, instantiate their children, and then call onFinishInflate().
599 */
Romain Guy9295ada2010-06-15 11:33:24 -0700600 private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
601 boolean finishInflate) throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602
603 final int depth = parser.getDepth();
604 int type;
605
606 while (((type = parser.next()) != XmlPullParser.END_TAG ||
607 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
608
609 if (type != XmlPullParser.START_TAG) {
610 continue;
611 }
612
613 final String name = parser.getName();
614
615 if (TAG_REQUEST_FOCUS.equals(name)) {
616 parseRequestFocus(parser, parent);
617 } else if (TAG_INCLUDE.equals(name)) {
618 if (parser.getDepth() == 0) {
619 throw new InflateException("<include /> cannot be the root element");
620 }
621 parseInclude(parser, parent, attrs);
622 } else if (TAG_MERGE.equals(name)) {
623 throw new InflateException("<merge /> must be the root element");
624 } else {
625 final View view = createViewFromTag(name, attrs);
626 final ViewGroup viewGroup = (ViewGroup) parent;
627 final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
Romain Guy9295ada2010-06-15 11:33:24 -0700628 rInflate(parser, view, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 viewGroup.addView(view, params);
630 }
631 }
632
Romain Guy9295ada2010-06-15 11:33:24 -0700633 if (finishInflate) parent.onFinishInflate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
635
636 private void parseRequestFocus(XmlPullParser parser, View parent)
637 throws XmlPullParserException, IOException {
638 int type;
639 parent.requestFocus();
640 final int currentDepth = parser.getDepth();
641 while (((type = parser.next()) != XmlPullParser.END_TAG ||
642 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
643 // Empty
644 }
645 }
646
647 private void parseInclude(XmlPullParser parser, View parent, AttributeSet attrs)
648 throws XmlPullParserException, IOException {
649
650 int type;
651
652 if (parent instanceof ViewGroup) {
653 final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
654 if (layout == 0) {
655 final String value = attrs.getAttributeValue(null, "layout");
656 if (value == null) {
657 throw new InflateException("You must specifiy a layout in the"
658 + " include tag: <include layout=\"@layout/layoutID\" />");
659 } else {
660 throw new InflateException("You must specifiy a valid layout "
661 + "reference. The layout ID " + value + " is not valid.");
662 }
663 } else {
664 final XmlResourceParser childParser =
665 getContext().getResources().getLayout(layout);
666
667 try {
668 final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
669
670 while ((type = childParser.next()) != XmlPullParser.START_TAG &&
671 type != XmlPullParser.END_DOCUMENT) {
672 // Empty.
673 }
674
675 if (type != XmlPullParser.START_TAG) {
676 throw new InflateException(childParser.getPositionDescription() +
677 ": No start tag found!");
678 }
679
680 final String childName = childParser.getName();
681
682 if (TAG_MERGE.equals(childName)) {
683 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700684 rInflate(childParser, parent, childAttrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 } else {
686 final View view = createViewFromTag(childName, childAttrs);
687 final ViewGroup group = (ViewGroup) parent;
688
689 // We try to load the layout params set in the <include /> tag. If
690 // they don't exist, we will rely on the layout params set in the
691 // included XML file.
692 // During a layoutparams generation, a runtime exception is thrown
693 // if either layout_width or layout_height is missing. We catch
694 // this exception and set localParams accordingly: true means we
695 // successfully loaded layout params from the <include /> tag,
696 // false means we need to rely on the included layout params.
697 ViewGroup.LayoutParams params = null;
698 try {
699 params = group.generateLayoutParams(attrs);
700 } catch (RuntimeException e) {
701 params = group.generateLayoutParams(childAttrs);
702 } finally {
703 if (params != null) {
704 view.setLayoutParams(params);
705 }
706 }
707
708 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700709 rInflate(childParser, view, childAttrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710
711 // Attempt to override the included layout's android:id with the
712 // one set on the <include /> tag itself.
713 TypedArray a = mContext.obtainStyledAttributes(attrs,
714 com.android.internal.R.styleable.View, 0, 0);
715 int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
716 // While we're at it, let's try to override android:visibility.
717 int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
718 a.recycle();
719
720 if (id != View.NO_ID) {
721 view.setId(id);
722 }
723
724 switch (visibility) {
725 case 0:
726 view.setVisibility(View.VISIBLE);
727 break;
728 case 1:
729 view.setVisibility(View.INVISIBLE);
730 break;
731 case 2:
732 view.setVisibility(View.GONE);
733 break;
734 }
735
736 group.addView(view);
737 }
738 } finally {
739 childParser.close();
740 }
741 }
742 } else {
743 throw new InflateException("<include /> can only be used inside of a ViewGroup");
744 }
745
746 final int currentDepth = parser.getDepth();
747 while (((type = parser.next()) != XmlPullParser.END_TAG ||
748 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
749 // Empty
750 }
751 }
752}