What is a LayoutInflater?
LayoutInflater
is a class used to create views from a layout resource (xml) file or a node of it (XmlPullParser
objects).
These can be a representation of either a single view or a view hierarchy.
Creating LayoutInflater object
To inflate a view, we need a LayoutInflater
object. Instead of creating new object, we use one of these methods normally to get an existing object with the context.
The first one is most commonly used because of its simplicity.
Here are sample usages of the last two methods.
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)
LayoutInflater inflater = (LayoutInflater)getSystemService(LayoutInflater.class)
Inflating views
To inflate views, LayoutInflater#inflate()
method can be used. It has four forms as listed below. One of the first two methods can be used if the source is a layout resource. Last two methods are used if the source is a layout resource node.
View inflate(int resource, ViewGroup root)
View inflate(int resource, ViewGroup root, boolean attachToRoot)
View inflate(XmlPullParser parser, ViewGroup root)
View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
root: It is a ViewGroup to which the newly created view hierarchy is about to attached.
attachToRoot: The first and third methods attaches the newly created view hierarchy to the root once it is created. However if you choose manually add it by ViewGroup#addView()
or attaching should be taken place at somewhere else, then you can choose the second or last method and set attachToRoot
as false.
For instance, inside Fragment
’s onCreateView()
and when creating a view as RecyclerView
’s itemView
. You should set attachToRoot
as false
in these two places because the attaching will be done somewhere else. If we set it as true
or use the first or third method in such places, it will throw an error.
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Using the result
If attachToRoot
is true, the result will be the root view. Otherwise it will be the newly created view hierarchy.
Theoretically all these methods returns the same thing - the root view. However, to us, they are not the same. Are they?
Some common mistakes
It is seen that setting root as null even if it is known. Root can be null if attachToRoot
is false
. However, it should be given if possible because it is used to create the correct subclass of LayoutParams
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…