blob: d24af52303d8b21477dbd209ee455c2597d07b9f [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 private Filter mFilter;
72
73 private final Object[] mConstructorArgs = new Object[2];
74
Gilles Debunne30301932010-06-16 18:32:00 -070075 private static final Class<?>[] mConstructorSignature = new Class[] {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 Context.class, AttributeSet.class};
77
Gilles Debunne30301932010-06-16 18:32:00 -070078 private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
79 new HashMap<String, Constructor<? extends View>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
81 private HashMap<String, Boolean> mFilterMap;
82
83 private static final String TAG_MERGE = "merge";
84 private static final String TAG_INCLUDE = "include";
85 private static final String TAG_REQUEST_FOCUS = "requestFocus";
86
87 /**
88 * Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed
89 * to be inflated.
90 *
91 */
92 public interface Filter {
93 /**
94 * Hook to allow clients of the LayoutInflater to restrict the set of Views
95 * that are allowed to be inflated.
96 *
97 * @param clazz The class object for the View that is about to be inflated
98 *
99 * @return True if this class is allowed to be inflated, or false otherwise
100 */
Gilles Debunnee6ac8b92010-06-17 10:55:04 -0700101 @SuppressWarnings("unchecked")
102 boolean onLoadClass(Class clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 }
104
105 public interface Factory {
106 /**
107 * Hook you can supply that is called when inflating from a LayoutInflater.
108 * You can use this to customize the tag names available in your XML
109 * layout files.
110 *
111 * <p>
112 * Note that it is good practice to prefix these custom names with your
113 * package (i.e., com.coolcompany.apps) to avoid conflicts with system
114 * names.
115 *
116 * @param name Tag name to be inflated.
117 * @param context The context the view is being created in.
118 * @param attrs Inflation attributes as specified in XML file.
119 *
120 * @return View Newly created view. Return null for the default
121 * behavior.
122 */
123 public View onCreateView(String name, Context context, AttributeSet attrs);
124 }
125
Dianne Hackborn625ac272010-09-17 18:29:22 -0700126 public interface Factory2 extends Factory {
127 /**
128 * Version of {@link #onCreateView(String, Context, AttributeSet)}
129 * that also supplies the parent that the view created view will be
130 * placed in.
131 *
132 * @param parent The parent that the created view will be placed
133 * in; <em>note that this may be null</em>.
134 * @param name Tag name to be inflated.
135 * @param context The context the view is being created in.
136 * @param attrs Inflation attributes as specified in XML file.
137 *
138 * @return View Newly created view. Return null for the default
139 * behavior.
140 */
141 public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
142 }
143
144 private static class FactoryMerger implements Factory2 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private final Factory mF1, mF2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700146 private final Factory2 mF12, mF22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Dianne Hackborn625ac272010-09-17 18:29:22 -0700148 FactoryMerger(Factory f1, Factory2 f12, Factory f2, Factory2 f22) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 mF1 = f1;
150 mF2 = f2;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700151 mF12 = f12;
152 mF22 = f22;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 }
154
155 public View onCreateView(String name, Context context, AttributeSet attrs) {
156 View v = mF1.onCreateView(name, context, attrs);
157 if (v != null) return v;
158 return mF2.onCreateView(name, context, attrs);
159 }
Dianne Hackborn625ac272010-09-17 18:29:22 -0700160
161 public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
162 View v = mF12 != null ? mF12.onCreateView(parent, name, context, attrs)
163 : mF1.onCreateView(name, context, attrs);
164 if (v != null) return v;
165 return mF22 != null ? mF22.onCreateView(parent, name, context, attrs)
166 : mF2.onCreateView(name, context, attrs);
167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 }
169
170 /**
171 * Create a new LayoutInflater instance associated with a particular Context.
172 * Applications will almost always want to use
173 * {@link Context#getSystemService Context.getSystemService()} to retrieve
174 * the standard {@link Context#LAYOUT_INFLATER_SERVICE Context.INFLATER_SERVICE}.
175 *
176 * @param context The Context in which this LayoutInflater will create its
177 * Views; most importantly, this supplies the theme from which the default
178 * values for their attributes are retrieved.
179 */
180 protected LayoutInflater(Context context) {
181 mContext = context;
182 }
183
184 /**
185 * Create a new LayoutInflater instance that is a copy of an existing
186 * LayoutInflater, optionally with its Context changed. For use in
187 * implementing {@link #cloneInContext}.
188 *
189 * @param original The original LayoutInflater to copy.
190 * @param newContext The new Context to use.
191 */
192 protected LayoutInflater(LayoutInflater original, Context newContext) {
193 mContext = newContext;
194 mFactory = original.mFactory;
Dianne Hackborn625ac272010-09-17 18:29:22 -0700195 mFactory2 = original.mFactory2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 mFilter = original.mFilter;
197 }
198
199 /**
200 * Obtains the LayoutInflater from the given context.
201 */
202 public static LayoutInflater from(Context context) {
203 LayoutInflater LayoutInflater =
204 (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
205 if (LayoutInflater == null) {
206 throw new AssertionError("LayoutInflater not found.");
207 }
208 return LayoutInflater;
209 }
210
211 /**
212 * Create a copy of the existing LayoutInflater object, with the copy
213 * pointing to a different Context than the original. This is used by
214 * {@link ContextThemeWrapper} to create a new LayoutInflater to go along
215 * with the new Context theme.
216 *
217 * @param newContext The new Context to associate with the new LayoutInflater.
218 * May be the same as the original Context if desired.
219 *
220 * @return Returns a brand spanking new LayoutInflater object associated with
221 * the given Context.
222 */
223 public abstract LayoutInflater cloneInContext(Context newContext);
224
225 /**
226 * Return the context we are running in, for access to resources, class
227 * loader, etc.
228 */
229 public Context getContext() {
230 return mContext;
231 }
232
233 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700234 * Return the current {@link Factory} (or null). This is called on each element
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 * name. If the factory returns a View, add that to the hierarchy. If it
236 * returns null, proceed to call onCreateView(name).
237 */
238 public final Factory getFactory() {
239 return mFactory;
240 }
241
242 /**
Dianne Hackborn625ac272010-09-17 18:29:22 -0700243 * Return the current {@link Factory2}. Returns null if no factory is set
244 * or the set factory does not implement the {@link Factory2} interface.
245 * This is called on each element
246 * 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 Factory2 getFactory2() {
250 return mFactory2;
251 }
252
253 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 * Attach a custom Factory interface for creating views while using
255 * this LayoutInflater. This must not be null, and can only be set once;
256 * after setting, you can not change the factory. This is
257 * called on each element name as the xml is parsed. If the factory returns
258 * a View, that is added to the hierarchy. If it returns null, the next
259 * factory default {@link #onCreateView} method is called.
260 *
261 * <p>If you have an existing
262 * LayoutInflater and want to add your own factory to it, use
263 * {@link #cloneInContext} to clone the existing instance and then you
264 * can use this function (once) on the returned new instance. This will
265 * merge your own factory with whatever factory the original instance is
266 * using.
267 */
268 public void setFactory(Factory factory) {
269 if (mFactorySet) {
270 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
271 }
272 if (factory == null) {
273 throw new NullPointerException("Given factory can not be null");
274 }
275 mFactorySet = true;
276 if (mFactory == null) {
277 mFactory = factory;
278 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700279 mFactory = new FactoryMerger(factory, null, mFactory, mFactory2);
280 }
281 }
282
283 /**
284 * Like {@link #setFactory}, but allows you to set a {@link Factory2}
285 * interface.
286 */
287 public void setFactory2(Factory2 factory) {
288 if (mFactorySet) {
289 throw new IllegalStateException("A factory has already been set on this LayoutInflater");
290 }
291 if (factory == null) {
292 throw new NullPointerException("Given factory can not be null");
293 }
294 mFactorySet = true;
295 if (mFactory == null) {
296 mFactory = mFactory2 = factory;
297 } else {
298 mFactory = new FactoryMerger(factory, factory, mFactory, mFactory2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300 }
301
302 /**
303 * @return The {@link Filter} currently used by this LayoutInflater to restrict the set of Views
304 * that are allowed to be inflated.
305 */
306 public Filter getFilter() {
307 return mFilter;
308 }
309
310 /**
311 * Sets the {@link Filter} to by this LayoutInflater. If a view is attempted to be inflated
312 * which is not allowed by the {@link Filter}, the {@link #inflate(int, ViewGroup)} call will
313 * throw an {@link InflateException}. This filter will replace any previous filter set on this
314 * LayoutInflater.
315 *
316 * @param filter The Filter which restricts the set of Views that are allowed to be inflated.
317 * This filter will replace any previous filter set on this LayoutInflater.
318 */
319 public void setFilter(Filter filter) {
320 mFilter = filter;
321 if (filter != null) {
322 mFilterMap = new HashMap<String, Boolean>();
323 }
324 }
325
326 /**
327 * Inflate a new view hierarchy from the specified xml resource. Throws
328 * {@link InflateException} if there is an error.
329 *
330 * @param resource ID for an XML layout resource to load (e.g.,
331 * <code>R.layout.main_page</code>)
332 * @param root Optional view to be the parent of the generated hierarchy.
333 * @return The root View of the inflated hierarchy. If root was supplied,
334 * this is the root View; otherwise it is the root of the inflated
335 * XML file.
336 */
337 public View inflate(int resource, ViewGroup root) {
338 return inflate(resource, root, root != null);
339 }
340
341 /**
342 * Inflate a new view hierarchy from the specified xml node. Throws
343 * {@link InflateException} if there is an error. *
344 * <p>
345 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
346 * reasons, view inflation relies heavily on pre-processing of XML files
347 * that is done at build time. Therefore, it is not currently possible to
348 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
349 *
350 * @param parser XML dom node containing the description of the view
351 * hierarchy.
352 * @param root Optional view to be the parent of the generated hierarchy.
353 * @return The root View of the inflated hierarchy. If root was supplied,
354 * this is the root View; otherwise it is the root of the inflated
355 * XML file.
356 */
357 public View inflate(XmlPullParser parser, ViewGroup root) {
358 return inflate(parser, root, root != null);
359 }
360
361 /**
362 * Inflate a new view hierarchy from the specified xml resource. Throws
363 * {@link InflateException} if there is an error.
364 *
365 * @param resource ID for an XML layout resource to load (e.g.,
366 * <code>R.layout.main_page</code>)
367 * @param root Optional view to be the parent of the generated hierarchy (if
368 * <em>attachToRoot</em> is true), or else simply an object that
369 * provides a set of LayoutParams values for root of the returned
370 * hierarchy (if <em>attachToRoot</em> is false.)
371 * @param attachToRoot Whether the inflated hierarchy should be attached to
372 * the root parameter? If false, root is only used to create the
373 * correct subclass of LayoutParams for the root view in the XML.
374 * @return The root View of the inflated hierarchy. If root was supplied and
375 * attachToRoot is true, this is root; otherwise it is the root of
376 * the inflated XML file.
377 */
378 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
379 if (DEBUG) System.out.println("INFLATING from resource: " + resource);
380 XmlResourceParser parser = getContext().getResources().getLayout(resource);
381 try {
382 return inflate(parser, root, attachToRoot);
383 } finally {
384 parser.close();
385 }
386 }
387
388 /**
389 * Inflate a new view hierarchy from the specified XML node. Throws
390 * {@link InflateException} if there is an error.
391 * <p>
392 * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;For performance
393 * reasons, view inflation relies heavily on pre-processing of XML files
394 * that is done at build time. Therefore, it is not currently possible to
395 * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
396 *
397 * @param parser XML dom node containing the description of the view
398 * hierarchy.
399 * @param root Optional view to be the parent of the generated hierarchy (if
400 * <em>attachToRoot</em> is true), or else simply an object that
401 * provides a set of LayoutParams values for root of the returned
402 * hierarchy (if <em>attachToRoot</em> is false.)
403 * @param attachToRoot Whether the inflated hierarchy should be attached to
404 * the root parameter? If false, root is only used to create the
405 * correct subclass of LayoutParams for the root view in the XML.
406 * @return The root View of the inflated hierarchy. If root was supplied and
407 * attachToRoot is true, this is root; otherwise it is the root of
408 * the inflated XML file.
409 */
410 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
411 synchronized (mConstructorArgs) {
412 final AttributeSet attrs = Xml.asAttributeSet(parser);
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700413 Context lastContext = (Context)mConstructorArgs[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 mConstructorArgs[0] = mContext;
415 View result = root;
416
417 try {
418 // Look for the root node.
419 int type;
420 while ((type = parser.next()) != XmlPullParser.START_TAG &&
421 type != XmlPullParser.END_DOCUMENT) {
422 // Empty
423 }
424
425 if (type != XmlPullParser.START_TAG) {
426 throw new InflateException(parser.getPositionDescription()
427 + ": No start tag found!");
428 }
429
430 final String name = parser.getName();
431
432 if (DEBUG) {
433 System.out.println("**************************");
434 System.out.println("Creating root view: "
435 + name);
436 System.out.println("**************************");
437 }
438
439 if (TAG_MERGE.equals(name)) {
440 if (root == null || !attachToRoot) {
441 throw new InflateException("<merge /> can be used only with a valid "
442 + "ViewGroup root and attachToRoot=true");
443 }
444
Romain Guy9295ada2010-06-15 11:33:24 -0700445 rInflate(parser, root, attrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 } else {
447 // Temp is the root view that was found in the xml
Dianne Hackborn625ac272010-09-17 18:29:22 -0700448 View temp = createViewFromTag(root, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449
450 ViewGroup.LayoutParams params = null;
451
452 if (root != null) {
453 if (DEBUG) {
454 System.out.println("Creating params from root: " +
455 root);
456 }
457 // Create layout params that match root, if supplied
458 params = root.generateLayoutParams(attrs);
459 if (!attachToRoot) {
460 // Set the layout params for temp if we are not
461 // attaching. (If we are, we use addView, below)
462 temp.setLayoutParams(params);
463 }
464 }
465
466 if (DEBUG) {
467 System.out.println("-----> start inflating children");
468 }
469 // Inflate all children under temp
Romain Guy9295ada2010-06-15 11:33:24 -0700470 rInflate(parser, temp, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 if (DEBUG) {
472 System.out.println("-----> done inflating children");
473 }
474
475 // We are supposed to attach all the views we found (int temp)
476 // to root. Do that now.
477 if (root != null && attachToRoot) {
478 root.addView(temp, params);
479 }
480
481 // Decide whether to return the root that was passed in or the
482 // top view found in xml.
483 if (root == null || !attachToRoot) {
484 result = temp;
485 }
486 }
487
488 } catch (XmlPullParserException e) {
489 InflateException ex = new InflateException(e.getMessage());
490 ex.initCause(e);
491 throw ex;
492 } catch (IOException e) {
493 InflateException ex = new InflateException(
494 parser.getPositionDescription()
495 + ": " + e.getMessage());
496 ex.initCause(e);
497 throw ex;
Dianne Hackborn9dae48e2010-08-26 10:20:01 -0700498 } finally {
499 // Don't retain static reference on context.
500 mConstructorArgs[0] = lastContext;
501 mConstructorArgs[1] = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 }
503
504 return result;
505 }
506 }
507
508 /**
509 * Low-level function for instantiating a view by name. This attempts to
510 * instantiate a view class of the given <var>name</var> found in this
511 * LayoutInflater's ClassLoader.
512 *
513 * <p>
514 * There are two things that can happen in an error case: either the
515 * exception describing the error will be thrown, or a null will be
516 * returned. You must deal with both possibilities -- the former will happen
517 * the first time createView() is called for a class of a particular name,
518 * the latter every time there-after for that class name.
519 *
520 * @param name The full name of the class to be instantiated.
521 * @param attrs The XML attributes supplied for this instance.
522 *
Gilles Debunne30301932010-06-16 18:32:00 -0700523 * @return View The newly instantiated view, or null.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 */
525 public final View createView(String name, String prefix, AttributeSet attrs)
526 throws ClassNotFoundException, InflateException {
Gilles Debunne30301932010-06-16 18:32:00 -0700527 Constructor<? extends View> constructor = sConstructorMap.get(name);
528 Class<? extends View> clazz = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
530 try {
531 if (constructor == null) {
532 // Class not found in the cache, see if it's real, and try to add it
Romain Guyd03b8802009-09-16 14:36:16 -0700533 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700534 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 if (mFilter != null && clazz != null) {
537 boolean allowed = mFilter.onLoadClass(clazz);
538 if (!allowed) {
539 failNotAllowed(name, prefix, attrs);
540 }
541 }
542 constructor = clazz.getConstructor(mConstructorSignature);
543 sConstructorMap.put(name, constructor);
544 } else {
545 // If we have a filter, apply it to cached constructor
546 if (mFilter != null) {
547 // Have we seen this name before?
548 Boolean allowedState = mFilterMap.get(name);
549 if (allowedState == null) {
550 // New class -- remember whether it is allowed
Romain Guyd03b8802009-09-16 14:36:16 -0700551 clazz = mContext.getClassLoader().loadClass(
Gilles Debunne30301932010-06-16 18:32:00 -0700552 prefix != null ? (prefix + name) : name).asSubclass(View.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553
554 boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
555 mFilterMap.put(name, allowed);
556 if (!allowed) {
557 failNotAllowed(name, prefix, attrs);
558 }
559 } else if (allowedState.equals(Boolean.FALSE)) {
560 failNotAllowed(name, prefix, attrs);
561 }
562 }
563 }
564
565 Object[] args = mConstructorArgs;
566 args[1] = attrs;
Gilles Debunne30301932010-06-16 18:32:00 -0700567 return constructor.newInstance(args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568
569 } catch (NoSuchMethodException e) {
570 InflateException ie = new InflateException(attrs.getPositionDescription()
571 + ": Error inflating class "
572 + (prefix != null ? (prefix + name) : name));
573 ie.initCause(e);
574 throw ie;
575
Gilles Debunne30301932010-06-16 18:32:00 -0700576 } catch (ClassCastException e) {
577 // If loaded class is not a View subclass
578 InflateException ie = new InflateException(attrs.getPositionDescription()
579 + ": Class is not a View "
580 + (prefix != null ? (prefix + name) : name));
581 ie.initCause(e);
582 throw ie;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 } catch (ClassNotFoundException e) {
584 // If loadClass fails, we should propagate the exception.
585 throw e;
586 } catch (Exception e) {
587 InflateException ie = new InflateException(attrs.getPositionDescription()
588 + ": Error inflating class "
Romain Guyd03b8802009-09-16 14:36:16 -0700589 + (clazz == null ? "<unknown>" : clazz.getName()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 ie.initCause(e);
591 throw ie;
592 }
593 }
594
595 /**
Gilles Debunne30301932010-06-16 18:32:00 -0700596 * Throw an exception because the specified class is not allowed to be inflated.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 */
598 private void failNotAllowed(String name, String prefix, AttributeSet attrs) {
599 InflateException ie = new InflateException(attrs.getPositionDescription()
600 + ": Class not allowed to be inflated "
601 + (prefix != null ? (prefix + name) : name));
602 throw ie;
603 }
604
605 /**
606 * This routine is responsible for creating the correct subclass of View
607 * given the xml element name. Override it to handle custom view objects. If
608 * you override this in your subclass be sure to call through to
609 * super.onCreateView(name) for names you do not recognize.
610 *
611 * @param name The fully qualified class name of the View to be create.
612 * @param attrs An AttributeSet of attributes to apply to the View.
613 *
614 * @return View The View created.
615 */
616 protected View onCreateView(String name, AttributeSet attrs)
617 throws ClassNotFoundException {
618 return createView(name, "android.view.", attrs);
619 }
620
Dianne Hackborn625ac272010-09-17 18:29:22 -0700621 /**
622 * Version of {@link #onCreateView(String, AttributeSet)} that also
623 * takes the future parent of the view being constructure. The default
624 * implementation simply calls {@link #onCreateView(String, AttributeSet)}.
625 *
626 * @param parent The future parent of the returned view. <em>Note that
627 * this may be null.</em>
628 * @param name The fully qualified class name of the View to be create.
629 * @param attrs An AttributeSet of attributes to apply to the View.
630 *
631 * @return View The View created.
632 */
633 protected View onCreateView(View parent, String name, AttributeSet attrs)
634 throws ClassNotFoundException {
635 return onCreateView(name, attrs);
636 }
637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 /*
639 * default visibility so the BridgeInflater can override it.
640 */
Dianne Hackborn625ac272010-09-17 18:29:22 -0700641 View createViewFromTag(View parent, String name, AttributeSet attrs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 if (name.equals("view")) {
643 name = attrs.getAttributeValue(null, "class");
644 }
645
646 if (DEBUG) System.out.println("******** Creating view: " + name);
647
648 try {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700649 View view;
650 if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
651 else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
652 else view = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653
654 if (view == null) {
655 if (-1 == name.indexOf('.')) {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700656 view = onCreateView(parent, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 } else {
658 view = createView(name, null, attrs);
659 }
660 }
661
662 if (DEBUG) System.out.println("Created view is: " + view);
663 return view;
664
665 } catch (InflateException e) {
666 throw e;
667
668 } catch (ClassNotFoundException e) {
669 InflateException ie = new InflateException(attrs.getPositionDescription()
670 + ": Error inflating class " + name);
671 ie.initCause(e);
672 throw ie;
673
674 } catch (Exception e) {
675 InflateException ie = new InflateException(attrs.getPositionDescription()
676 + ": Error inflating class " + name);
677 ie.initCause(e);
678 throw ie;
679 }
680 }
681
682 /**
683 * Recursive method used to descend down the xml hierarchy and instantiate
684 * views, instantiate their children, and then call onFinishInflate().
685 */
Romain Guy9295ada2010-06-15 11:33:24 -0700686 private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
687 boolean finishInflate) throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688
689 final int depth = parser.getDepth();
690 int type;
691
692 while (((type = parser.next()) != XmlPullParser.END_TAG ||
693 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
694
695 if (type != XmlPullParser.START_TAG) {
696 continue;
697 }
698
699 final String name = parser.getName();
700
701 if (TAG_REQUEST_FOCUS.equals(name)) {
702 parseRequestFocus(parser, parent);
703 } else if (TAG_INCLUDE.equals(name)) {
704 if (parser.getDepth() == 0) {
705 throw new InflateException("<include /> cannot be the root element");
706 }
707 parseInclude(parser, parent, attrs);
708 } else if (TAG_MERGE.equals(name)) {
709 throw new InflateException("<merge /> must be the root element");
710 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700711 final View view = createViewFromTag(parent, name, attrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 final ViewGroup viewGroup = (ViewGroup) parent;
713 final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
Romain Guy9295ada2010-06-15 11:33:24 -0700714 rInflate(parser, view, attrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 viewGroup.addView(view, params);
716 }
717 }
718
Romain Guy9295ada2010-06-15 11:33:24 -0700719 if (finishInflate) parent.onFinishInflate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721
722 private void parseRequestFocus(XmlPullParser parser, View parent)
723 throws XmlPullParserException, IOException {
724 int type;
725 parent.requestFocus();
726 final int currentDepth = parser.getDepth();
727 while (((type = parser.next()) != XmlPullParser.END_TAG ||
728 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
729 // Empty
730 }
731 }
732
733 private void parseInclude(XmlPullParser parser, View parent, AttributeSet attrs)
734 throws XmlPullParserException, IOException {
735
736 int type;
737
738 if (parent instanceof ViewGroup) {
739 final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
740 if (layout == 0) {
741 final String value = attrs.getAttributeValue(null, "layout");
742 if (value == null) {
743 throw new InflateException("You must specifiy a layout in the"
744 + " include tag: <include layout=\"@layout/layoutID\" />");
745 } else {
746 throw new InflateException("You must specifiy a valid layout "
747 + "reference. The layout ID " + value + " is not valid.");
748 }
749 } else {
750 final XmlResourceParser childParser =
751 getContext().getResources().getLayout(layout);
752
753 try {
754 final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
755
756 while ((type = childParser.next()) != XmlPullParser.START_TAG &&
757 type != XmlPullParser.END_DOCUMENT) {
758 // Empty.
759 }
760
761 if (type != XmlPullParser.START_TAG) {
762 throw new InflateException(childParser.getPositionDescription() +
763 ": No start tag found!");
764 }
765
766 final String childName = childParser.getName();
767
768 if (TAG_MERGE.equals(childName)) {
769 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700770 rInflate(childParser, parent, childAttrs, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 } else {
Dianne Hackborn625ac272010-09-17 18:29:22 -0700772 final View view = createViewFromTag(parent, childName, childAttrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 final ViewGroup group = (ViewGroup) parent;
774
775 // We try to load the layout params set in the <include /> tag. If
776 // they don't exist, we will rely on the layout params set in the
777 // included XML file.
778 // During a layoutparams generation, a runtime exception is thrown
779 // if either layout_width or layout_height is missing. We catch
780 // this exception and set localParams accordingly: true means we
781 // successfully loaded layout params from the <include /> tag,
782 // false means we need to rely on the included layout params.
783 ViewGroup.LayoutParams params = null;
784 try {
785 params = group.generateLayoutParams(attrs);
786 } catch (RuntimeException e) {
787 params = group.generateLayoutParams(childAttrs);
788 } finally {
789 if (params != null) {
790 view.setLayoutParams(params);
791 }
792 }
793
794 // Inflate all children.
Romain Guy9295ada2010-06-15 11:33:24 -0700795 rInflate(childParser, view, childAttrs, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796
797 // Attempt to override the included layout's android:id with the
798 // one set on the <include /> tag itself.
799 TypedArray a = mContext.obtainStyledAttributes(attrs,
800 com.android.internal.R.styleable.View, 0, 0);
801 int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
802 // While we're at it, let's try to override android:visibility.
803 int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
804 a.recycle();
805
806 if (id != View.NO_ID) {
807 view.setId(id);
808 }
809
810 switch (visibility) {
811 case 0:
812 view.setVisibility(View.VISIBLE);
813 break;
814 case 1:
815 view.setVisibility(View.INVISIBLE);
816 break;
817 case 2:
818 view.setVisibility(View.GONE);
819 break;
820 }
821
822 group.addView(view);
823 }
824 } finally {
825 childParser.close();
826 }
827 }
828 } else {
829 throw new InflateException("<include /> can only be used inside of a ViewGroup");
830 }
831
832 final int currentDepth = parser.getDepth();
833 while (((type = parser.next()) != XmlPullParser.END_TAG ||
834 parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
835 // Empty
836 }
837 }
838}