Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package android.view;
 
 
 
This class is used to instantiate layout XML file into its corresponding View objects. It is never be used directly -- use android.app.Activity.getLayoutInflater() or android.content.Context.getSystemService(java.lang.String) 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 LayoutInflater.Factory for your own views, you can use cloneInContext(android.content.Context) to clone an existing ViewFactory, and then call setFactory(android.view.LayoutInflater.Factory) 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.)

 
 public abstract class LayoutInflater {
     private final boolean DEBUG = false;

    
This field should be made private, so it is hidden from the SDK.
 
     protected final Context mContext;
 
     // these are optional, set by the caller
     private boolean mFactorySet;
     private Factory mFactory;
     private Filter mFilter;
 
     private final Object[] mConstructorArgs = new Object[2];
 
     private static final Class[] mConstructorSignature = new Class[] {
             Context.classAttributeSet.class};
 
     private static final HashMap<StringConstructorsConstructorMap =
             new HashMap<StringConstructor>();
     
     private HashMap<StringBooleanmFilterMap;
 
     private static final String TAG_MERGE = "merge";
     private static final String TAG_INCLUDE = "include";
     private static final String TAG_REQUEST_FOCUS = "requestFocus";

    
Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed to be inflated.
 
     public interface Filter {
        
Hook to allow clients of the LayoutInflater to restrict the set of Views that are allowed to be inflated.

Parameters:
clazz The class object for the View that is about to be inflated
Returns:
True if this class is allowed to be inflated, or false otherwise
 
        boolean onLoadClass(Class clazz);
    }
    
    public interface Factory {
        
Hook you can supply that is called when inflating from a LayoutInflater. You can use this to customize the tag names available in your XML layout files.

Note that it is good practice to prefix these custom names with your package (i.e., com.coolcompany.apps) to avoid conflicts with system names.

Parameters:
name Tag name to be inflated.
context The context the view is being created in.
attrs Inflation attributes as specified in XML file.
Returns:
View Newly created view. Return null for the default behavior.
        public View onCreateView(String nameContext contextAttributeSet attrs);
    }
    private static class FactoryMerger implements Factory {
        private final Factory mF1mF2;
        
        FactoryMerger(Factory f1Factory f2) {
             = f1;
             = f2;
        }
        
        public View onCreateView(String nameContext contextAttributeSet attrs) {
            View v = .onCreateView(namecontextattrs);
            if (v != nullreturn v;
            return .onCreateView(namecontextattrs);
        }
    }
    
    
Create a new LayoutInflater instance associated with a particular Context. Applications will almost always want to use Context.getSystemService() to retrieve the standard Context.INFLATER_SERVICE.

Parameters:
context The Context in which this LayoutInflater will create its Views; most importantly, this supplies the theme from which the default values for their attributes are retrieved.
    protected LayoutInflater(Context context) {
         = context;
    }

    
Create a new LayoutInflater instance that is a copy of an existing LayoutInflater, optionally with its Context changed. For use in implementing cloneInContext(android.content.Context).

Parameters:
original The original LayoutInflater to copy.
newContext The new Context to use.
    protected LayoutInflater(LayoutInflater originalContext newContext) {
         = newContext;
         = original.mFactory;
         = original.mFilter;
    }
    
    
Obtains the LayoutInflater from the given context.
    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflatercontext.getSystemService(.);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

    
Create a copy of the existing LayoutInflater object, with the copy pointing to a different Context than the original. This is used by ContextThemeWrapper to create a new LayoutInflater to go along with the new Context theme.

Parameters:
newContext The new Context to associate with the new LayoutInflater. May be the same as the original Context if desired.
Returns:
Returns a brand spanking new LayoutInflater object associated with the given Context.
    public abstract LayoutInflater cloneInContext(Context newContext);
    
    
Return the context we are running in, for access to resources, class loader, etc.
    public Context getContext() {
        return ;
    }

    
Return the current 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).
    public final Factory getFactory() {
        return ;
    }

    
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 onCreateView(java.lang.String,android.util.AttributeSet) method is called.

If you have an existing LayoutInflater and want to add your own factory to it, use cloneInContext(android.content.Context) 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.

    public void setFactory(Factory factory) {
        if () {
            throw new IllegalStateException("A factory has already been set on this LayoutInflater");
        }
        if (factory == null) {
            throw new NullPointerException("Given factory can not be null");
        }
         = true;
        if ( == null) {
             = factory;
        } else {
             = new FactoryMerger(factory);
        }
    }

    

Returns:
The LayoutInflater.Filter currently used by this LayoutInflater to restrict the set of Views that are allowed to be inflated.
    public Filter getFilter() {
        return ;
    }
    
    
Sets the LayoutInflater.Filter to by this LayoutInflater. If a view is attempted to be inflated which is not allowed by the LayoutInflater.Filter, the inflate(int,android.view.ViewGroup) call will throw an InflateException. This filter will replace any previous filter set on this LayoutInflater.

Parameters:
filter The Filter which restricts the set of Views that are allowed to be inflated. This filter will replace any previous filter set on this LayoutInflater.
    public void setFilter(Filter filter) {
         = filter;
        if (filter != null) {
             = new HashMap<StringBoolean>();
        }
    }

    
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters:
resource ID for an XML layout resource to load (e.g., R.layout.main_page)
root Optional view to be the parent of the generated hierarchy.
Returns:
The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
    public View inflate(int resourceViewGroup root) {
        return inflate(resourcerootroot != null);
    }

    
Inflate a new view hierarchy from the specified xml node. Throws 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.

Parameters:
parser XML dom node containing the description of the view hierarchy.
root Optional view to be the parent of the generated hierarchy.
Returns:
The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
    public View inflate(XmlPullParser parserViewGroup root) {
        return inflate(parserrootroot != null);
    }

    
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters:
resource ID for an XML layout resource to load (e.g., R.layout.main_page)
root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
Returns:
The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.
    public View inflate(int resourceViewGroup rootboolean attachToRoot) {
        if (..println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().getLayout(resource);
        try {
            return inflate(parserrootattachToRoot);
        } finally {
            parser.close();
        }
    }

    
Inflate a new view hierarchy from the specified XML node. Throws 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.

Parameters:
parser XML dom node containing the description of the view hierarchy.
root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
Returns:
The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.
    public View inflate(XmlPullParser parserViewGroup rootboolean attachToRoot) {
        synchronized () {
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context)[0];
            [0] = ;
            View result = root;
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != . &&
                        type != .) {
                    // Empty
                }
                if (type != .) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
                final String name = parser.getName();
                
                if () {
                    ..println("**************************");
                    ..println("Creating root view: "
                            + name);
                    ..println("**************************");
                }
                if (.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }
                    rInflate(parserrootattrs);
                } else {
                    // Temp is the root view that was found in the xml
                    View temp = createViewFromTag(nameattrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        if () {
                            ..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 () {
                        ..println("-----> start inflating children");
                    }
                    // Inflate all children under temp
                    rInflate(parsertempattrs);
                    if () {
                        ..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(tempparams);
                    }
                    // 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.
                [0] = lastContext;
                [1] = null;
            }
            return result;
        }
    }

    
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.

Parameters:
name The full name of the class to be instantiated.
attrs The XML attributes supplied for this instance.
Returns:
View The newly instantied view, or null.
    public final View createView(String nameString prefixAttributeSet attrs)
            throws ClassNotFoundExceptionInflateException {
        Constructor constructor = .get(name);
        Class clazz = null;
        try {
            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = .getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name);
                
                if ( != null && clazz != null) {
                    boolean allowed = .onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(nameprefixattrs);
                    }
                }
                constructor = clazz.getConstructor();
                .put(nameconstructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if ( != null) {
                    // Have we seen this name before?
                    Boolean allowedState = .get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = .getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name);
                        
                        boolean allowed = clazz != null && .onLoadClass(clazz);
                        .put(nameallowed);
                        if (!allowed) {
                            failNotAllowed(nameprefixattrs);
                        }
                    } else if (allowedState.equals(.)) {
                        failNotAllowed(nameprefixattrs);
                    }
                }
            }
            Object[] args = ;
            args[1] = attrs;
            return (Viewconstructor.newInstance(args);
        } catch (NoSuchMethodException e) {
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class "
                    + (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;
        }
    }

    
Throw an excpetion because the specified class is not allowed to be inflated.
    private void failNotAllowed(String nameString prefixAttributeSet attrs) {
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Class not allowed to be inflated "
                + (prefix != null ? (prefix + name) : name));
        throw ie;
    }

    
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.

Parameters:
name The fully qualified class name of the View to be create.
attrs An AttributeSet of attributes to apply to the View.
Returns:
View The View created.
    protected View onCreateView(String nameAttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name"android.view."attrs);
    }
    /*
     * default visibility so the BridgeInflater can override it.
     */
    View createViewFromTag(String nameAttributeSet attrs) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null"class");
        }
        if (..println("******** Creating view: " + name);
        try {
            View view = ( == null) ? null : .onCreateView(name,
                    attrs);
            if (view == null) {
                if (-1 == name.indexOf('.')) {
                    view = onCreateView(nameattrs);
                } else {
                    view = createView(namenullattrs);
                }
            }
            if (..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;
        }
    }

    
Recursive method used to descend down the xml hierarchy and instantiate views, instantiate their children, and then call onFinishInflate().
    private void rInflate(XmlPullParser parserView parentfinal AttributeSet attrs)
            throws XmlPullParserExceptionIOException {
        final int depth = parser.getDepth();
        int type;
        while (((type = parser.next()) != . ||
                parser.getDepth() > depth) && type != .) {
            if (type != .) {
                continue;
            }
            final String name = parser.getName();
            
            if (.equals(name)) {
                parseRequestFocus(parserparent);
            } else if (.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parserparentattrs);
            } else if (.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(nameattrs);
                final ViewGroup viewGroup = (ViewGroupparent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parserviewattrs);
                viewGroup.addView(viewparams);
            }
        }
        parent.onFinishInflate();
    }
    private void parseRequestFocus(XmlPullParser parserView parent)
            throws XmlPullParserExceptionIOException {
        int type;
        parent.requestFocus();
        final int currentDepth = parser.getDepth();
        while (((type = parser.next()) != . ||
                parser.getDepth() > currentDepth) && type != .) {
            // Empty
        }
    }
    private void parseInclude(XmlPullParser parserView parentAttributeSet attrs)
            throws XmlPullParserExceptionIOException {
        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()) != . &&
                            type != .) {
                        // Empty.
                    }
                    if (type != .) {
                        throw new InflateException(childParser.getPositionDescription() +
                                ": No start tag found!");
                    }
                    final String childName = childParser.getName();
                    if (.equals(childName)) {
                        // Inflate all children.
                        rInflate(childParserparentchildAttrs);
                    } else {
                        final View view = createViewFromTag(childNamechildAttrs);
                        final ViewGroup group = (ViewGroupparent;
                        // 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(childParserviewchildAttrs);
                        // Attempt to override the included layout's android:id with the
                        // one set on the <include /> tag itself.
                        TypedArray a = .obtainStyledAttributes(attrs,
                            ....., 0, 0);
                        int id = a.getResourceId(......);
                        // While we're at it, let's try to override android:visibility.
                        int visibility = a.getInt(....., -1);
                        a.recycle();
                        if (id != .) {
                            view.setId(id);
                        }
                        switch (visibility) {
                            case 0:
                                view.setVisibility(.);
                                break;
                            case 1:
                                view.setVisibility(.);
                                break;
                            case 2:
                                view.setVisibility(.);
                                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()) != . ||
                parser.getDepth() > currentDepth) && type != .) {
            // Empty
        }
    }    
New to GrepCode? Check out our FAQ X