LayoutInflaterpublic abstract class LayoutInflater extends Object Instantiates a layout XML file into its corresponding {@link android.view.View}
objects. It is never used directly. Instead, use
{@link android.app.Activity#getLayoutInflater()} or
{@link Context#getSystemService} to retrieve a standard LayoutInflater instance
that is already hooked up to the current context and correctly configured
for the device you are running on. For example:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
To create a new LayoutInflater with an additional {@link Factory} for your
own views, you can use {@link #cloneInContext} to clone an existing
ViewFactory, and then call {@link #setFactory} on it to include your
Factory.
For performance reasons, view inflation relies heavily on pre-processing of
XML files that is done at build time. Therefore, it is not currently possible
to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
it only works with an XmlPullParser returned from a compiled resource
(R.something file.) |
Fields Summary |
---|
private static final String | TAG | private static final boolean | DEBUG | protected final android.content.Context | mContextThis field should be made private, so it is hidden from the SDK.
{@hide} | private boolean | mFactorySet | private Factory | mFactory | private Factory2 | mFactory2 | private Factory2 | mPrivateFactory | private Filter | mFilter | final Object[] | mConstructorArgs | static final Class[] | mConstructorSignature | private static final HashMap | sConstructorMap | private HashMap | mFilterMap | private static final String | TAG_MERGE | private static final String | TAG_INCLUDE | private static final String | TAG_1995 | private static final String | TAG_REQUEST_FOCUS | private static final String | TAG_TAG | private static final int[] | ATTRS_THEME |
Constructors Summary |
---|
protected LayoutInflater(android.content.Context context)Create a new LayoutInflater instance associated with a particular Context.
Applications will almost always want to use
{@link Context#getSystemService Context.getSystemService()} to retrieve
the standard {@link Context#LAYOUT_INFLATER_SERVICE Context.INFLATER_SERVICE}.
mContext = context;
| protected LayoutInflater(LayoutInflater original, android.content.Context newContext)Create a new LayoutInflater instance that is a copy of an existing
LayoutInflater, optionally with its Context changed. For use in
implementing {@link #cloneInContext}.
mContext = newContext;
mFactory = original.mFactory;
mFactory2 = original.mFactory2;
mPrivateFactory = original.mPrivateFactory;
setFilter(original.mFilter);
|
Methods Summary |
---|
public abstract android.view.LayoutInflater | cloneInContext(android.content.Context newContext)Create a copy of the existing LayoutInflater object, with the copy
pointing to a different Context than the original. This is used by
{@link ContextThemeWrapper} to create a new LayoutInflater to go along
with the new Context theme.
| public final View | createView(java.lang.String name, java.lang.String prefix, android.util.AttributeSet attrs)Low-level function for instantiating a view by name. This attempts to
instantiate a view class of the given name found in this
LayoutInflater's ClassLoader.
There are two things that can happen in an error case: either the
exception describing the error will be thrown, or a null will be
returned. You must deal with both possibilities -- the former will happen
the first time createView() is called for a class of a particular name,
the latter every time there-after for that class name.
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
constructor.setAccessible(true);
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()));
ie.initCause(e);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
| View | createViewFromTag(View parent, java.lang.String name, android.util.AttributeSet attrs, boolean inheritContext)Creates a view from a tag name using the supplied attribute set.
If {@code inheritContext} is true and the parent is non-null, the view
will be inflated in parent view's context. If the view specifies a
<theme> attribute, the inflation context will be wrapped with the
specified theme.
Note: Default visibility so the BridgeInflater can override it.
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
Context viewContext;
if (parent != null && inheritContext) {
viewContext = parent.getContext();
} else {
viewContext = mContext;
}
// Apply a theme wrapper, if requested.
final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
viewContext = new ContextThemeWrapper(viewContext, themeResId);
}
ta.recycle();
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(viewContext, attrs);
}
if (DEBUG) System.out.println("******** Creating view: " + name);
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, viewContext, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, viewContext, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = viewContext;
try {
if (-1 == name.indexOf('.")) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
if (DEBUG) System.out.println("Created view is: " + view);
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
| private void | failNotAllowed(java.lang.String name, java.lang.String prefix, android.util.AttributeSet attrs)Throw an exception because the specified class is not allowed to be inflated.
throw new InflateException(attrs.getPositionDescription()
+ ": Class not allowed to be inflated "
+ (prefix != null ? (prefix + name) : name));
| public static android.view.LayoutInflater | from(android.content.Context context)Obtains the LayoutInflater from the given context.
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
| public android.content.Context | getContext()Return the context we are running in, for access to resources, class
loader, etc.
return mContext;
| public final android.view.LayoutInflater$Factory | getFactory()Return the current {@link Factory} (or null). This is called on each element
name. If the factory returns a View, add that to the hierarchy. If it
returns null, proceed to call onCreateView(name).
return mFactory;
| public final android.view.LayoutInflater$Factory2 | getFactory2()Return the current {@link Factory2}. Returns null if no factory is set
or the set factory does not implement the {@link Factory2} interface.
This is called on each element
name. If the factory returns a View, add that to the hierarchy. If it
returns null, proceed to call onCreateView(name).
return mFactory2;
| public android.view.LayoutInflater$Filter | getFilter()
return mFilter;
| public View | inflate(int resource, ViewGroup root)Inflate a new view hierarchy from the specified xml resource. Throws
{@link InflateException} if there is an error.
return inflate(resource, root, root != null);
| public View | inflate(org.xmlpull.v1.XmlPullParser parser, ViewGroup root)Inflate a new view hierarchy from the specified xml node. Throws
{@link InflateException} if there is an error. *
Important For performance
reasons, view inflation relies heavily on pre-processing of XML files
that is done at build time. Therefore, it is not currently possible to
use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
return inflate(parser, root, root != null);
| public View | inflate(int resource, ViewGroup root, boolean attachToRoot)Inflate a new view hierarchy from the specified xml resource. Throws
{@link InflateException} if there is an error.
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
| public View | inflate(org.xmlpull.v1.XmlPullParser parser, ViewGroup root, boolean attachToRoot)Inflate a new view hierarchy from the specified XML node. Throws
{@link InflateException} if there is an error.
Important For performance
reasons, view inflation relies heavily on pre-processing of XML files
that is done at build time. Therefore, it is not currently possible to
use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, attrs, false, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, attrs, false);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp
rInflate(parser, temp, attrs, true, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
| protected View | onCreateView(java.lang.String name, android.util.AttributeSet attrs)This routine is responsible for creating the correct subclass of View
given the xml element name. Override it to handle custom view objects. If
you override this in your subclass be sure to call through to
super.onCreateView(name) for names you do not recognize.
return createView(name, "android.view.", attrs);
| protected View | onCreateView(View parent, java.lang.String name, android.util.AttributeSet attrs)Version of {@link #onCreateView(String, AttributeSet)} that also
takes the future parent of the view being constructed. The default
implementation simply calls {@link #onCreateView(String, AttributeSet)}.
return onCreateView(name, attrs);
| private void | parseInclude(org.xmlpull.v1.XmlPullParser parser, View parent, android.util.AttributeSet attrs, boolean inheritContext)
int type;
if (parent instanceof ViewGroup) {
final int layout = attrs.getAttributeResourceValue(null, "layout", 0);
if (layout == 0) {
final String value = attrs.getAttributeValue(null, "layout");
if (value == null) {
throw new InflateException("You must specifiy a layout in the"
+ " include tag: <include layout=\"@layout/layoutID\" />");
} else {
throw new InflateException("You must specifiy a valid layout "
+ "reference. The layout ID " + value + " is not valid.");
}
} else {
final XmlResourceParser childParser =
getContext().getResources().getLayout(layout);
try {
final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
while ((type = childParser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty.
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(childParser.getPositionDescription() +
": No start tag found!");
}
final String childName = childParser.getName();
if (TAG_MERGE.equals(childName)) {
// Inflate all children.
rInflate(childParser, parent, childAttrs, false, inheritContext);
} else {
final View view = createViewFromTag(parent, childName, childAttrs,
inheritContext);
final ViewGroup group = (ViewGroup) parent;
// We try to load the layout params set in the <include /> tag. If
// they don't exist, we will rely on the layout params set in the
// included XML file.
// During a layoutparams generation, a runtime exception is thrown
// if either layout_width or layout_height is missing. We catch
// this exception and set localParams accordingly: true means we
// successfully loaded layout params from the <include /> tag,
// false means we need to rely on the included layout params.
ViewGroup.LayoutParams params = null;
try {
params = group.generateLayoutParams(attrs);
} catch (RuntimeException e) {
params = group.generateLayoutParams(childAttrs);
} finally {
if (params != null) {
view.setLayoutParams(params);
}
}
// Inflate all children.
rInflate(childParser, view, childAttrs, true, true);
// Attempt to override the included layout's android:id with the
// one set on the <include /> tag itself.
TypedArray a = mContext.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.View, 0, 0);
int id = a.getResourceId(com.android.internal.R.styleable.View_id, View.NO_ID);
// While we're at it, let's try to override android:visibility.
int visibility = a.getInt(com.android.internal.R.styleable.View_visibility, -1);
a.recycle();
if (id != View.NO_ID) {
view.setId(id);
}
switch (visibility) {
case 0:
view.setVisibility(View.VISIBLE);
break;
case 1:
view.setVisibility(View.INVISIBLE);
break;
case 2:
view.setVisibility(View.GONE);
break;
}
group.addView(view);
}
} finally {
childParser.close();
}
}
} else {
throw new InflateException("<include /> can only be used inside of a ViewGroup");
}
final int currentDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
// Empty
}
| private void | parseRequestFocus(org.xmlpull.v1.XmlPullParser parser, View view)Parses a <request-focus> element and requests focus on
the containing View.
int type;
view.requestFocus();
final int currentDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
// Empty
}
| private void | parseViewTag(org.xmlpull.v1.XmlPullParser parser, View view, android.util.AttributeSet attrs)Parses a <tag> element and sets a keyed tag on the
containing View.
int type;
final TypedArray ta = mContext.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.ViewTag);
final int key = ta.getResourceId(com.android.internal.R.styleable.ViewTag_id, 0);
final CharSequence value = ta.getText(com.android.internal.R.styleable.ViewTag_value);
view.setTag(key, value);
ta.recycle();
final int currentDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) {
// Empty
}
| void | rInflate(org.xmlpull.v1.XmlPullParser parser, View parent, android.util.AttributeSet attrs, boolean finishInflate, boolean inheritContext)Recursive method used to descend down the xml hierarchy and instantiate
views, instantiate their children, and then call onFinishInflate().
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, parent, attrs, inheritContext);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, attrs, inheritContext);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) parent.onFinishInflate();
| public void | setFactory(android.view.LayoutInflater$Factory factory)Attach a custom Factory interface for creating views while using
this LayoutInflater. This must not be null, and can only be set once;
after setting, you can not change the factory. This is
called on each element name as the xml is parsed. If the factory returns
a View, that is added to the hierarchy. If it returns null, the next
factory default {@link #onCreateView} method is called.
If you have an existing
LayoutInflater and want to add your own factory to it, use
{@link #cloneInContext} to clone the existing instance and then you
can use this function (once) on the returned new instance. This will
merge your own factory with whatever factory the original instance is
using.
if (mFactorySet) {
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
if (factory == null) {
throw new NullPointerException("Given factory can not be null");
}
mFactorySet = true;
if (mFactory == null) {
mFactory = factory;
} else {
mFactory = new FactoryMerger(factory, null, mFactory, mFactory2);
}
| public void | setFactory2(android.view.LayoutInflater$Factory2 factory)Like {@link #setFactory}, but allows you to set a {@link Factory2}
interface.
if (mFactorySet) {
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
if (factory == null) {
throw new NullPointerException("Given factory can not be null");
}
mFactorySet = true;
if (mFactory == null) {
mFactory = mFactory2 = factory;
} else {
mFactory = mFactory2 = new FactoryMerger(factory, factory, mFactory, mFactory2);
}
| public void | setFilter(android.view.LayoutInflater$Filter filter)Sets the {@link Filter} to by this LayoutInflater. If a view is attempted to be inflated
which is not allowed by the {@link Filter}, the {@link #inflate(int, ViewGroup)} call will
throw an {@link InflateException}. This filter will replace any previous filter set on this
LayoutInflater.
mFilter = filter;
if (filter != null) {
mFilterMap = new HashMap<String, Boolean>();
}
| public void | setPrivateFactory(android.view.LayoutInflater$Factory2 factory)
if (mPrivateFactory == null) {
mPrivateFactory = factory;
} else {
mPrivateFactory = new FactoryMerger(factory, factory, mPrivateFactory, mPrivateFactory);
}
|
|