When writing Android programs, you may sometimes write custom views and use the Inflater object to parse the layout file into a View. This article aims to summarize the methods for obtaining LayoutInflater objects.
1. If you can obtain the context object, you can use the following methods:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View child = inflater.inflate(R.layout.child, null);
Or
LayoutInflater inflater = LayoutInflater.from(context);View child = inflater.inflate(R.layout.child, null);
2. In an Activity, you can use the following methods:
View child = getLayoutInflater().inflate(R.layout.child, item, false);
Or
View view; LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.mylayout, null);
Both method 1 and method 2 actually use context (). getSystemService ().
3. static View method:
View view=View.inflate(context, R.layout.child, 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 = LayoutInflater.from(context); return factory.inflate(resource, root); }
LayoutInflater. from (context) is actually packaging 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.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; }