SoFunction
Updated on 2025-04-09

Android development method to obtain LayoutInflater object

This article describes the method of obtaining LayoutInflater object in Android development. Share it for your reference, as follows:

When writing Android programs, you sometimes write a custom View, using the Inflater object to parse the layout file into a View. The main purpose of this article is to summarize the methods of obtaining LayoutInflater objects.

1. If you can obtain the context object, there are several methods:

LayoutInflater inflater = (LayoutInflater)(Context.LAYOUT_INFLATER_SERVICE);
View child = (, null);

or:

LayoutInflater inflater = (context);
View child = (, null);

2. In an Activity, there can be the following methods:

View child = getLayoutInflater().inflate(, item, false);

or:

View view;
LayoutInflater inflater = (LayoutInflater)  getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (, null);

Method 1 and method 2 are actually both use context().getSystemService()

3. Static method of using View:

View view=(context, , null)

The source code of inflate is as follows:

/**
 * Inflate a view from an XML resource. This convenience method wraps the {@link
 * LayoutInflater} class, which provides a full range of options for view inflation.
 *
 * @param context The Context object for your activity or application.
 * @param resource The resource ID to inflate
 * @param root A view group that will be the parent. Used to properly inflate the
 * layout_* parameters.
 * @see LayoutInflater
 */
public static View inflate(Context context, int resource, ViewGroup root) {
  LayoutInflater factory = (context);
  return (resource, root);
}

(context) is actually a wrapper for method 1, you can refer to the following source code:

/**
 * Obtains the LayoutInflater from the given context.
 */
public static LayoutInflater from(Context context) {
  LayoutInflater LayoutInflater =
      (LayoutInflater) (Context.LAYOUT_INFLATER_SERVICE);
  if (LayoutInflater == null) {
    throw new AssertionError("LayoutInflater not found.");
  }
  return LayoutInflater;
}

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android control usage summary》、《A summary of Android SMS and Telephone Operation Tips"and"Android multimedia operation skills summary (audio, video, recording, etc.)

I hope this article will be helpful to everyone's Android programming design.