LayoutInflater 的基本用法
LayoutInflater 是用来加载布局的。一般在 Activity 里会调用 setContentView 来设置布局。其实 setcontentView 内部也是调用LayoutInflater 来加载布局的。只不过这部分源码是内部的没有公开。
首先要获取到 LayoutInflater 的实例,有2种方法。
1.LayoutInflater layoutInflater = LayoutInflater.from(context);
2.LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService.LAYOUT_INFLATER_SERVICE;
其实第一种写法就是第二种,只是 Android 给我们做了一下封装。得到实例后就可以调用他的 inflate 方法来加载布局了。
layoutInflater.inflate(resourceId,root)
inflate 接收2个参数,第一个参数就是要加载的布局 id,第二个参数是指给该布局的外部再嵌套一层父布局,如果不需要就直接传 null。
举个小例子
通过一个小例子,更加直观的看一下LayoutInflater的用法。比如说当前有一个项目,其中MainActivity对应的布局文件叫做activity_main.xml,代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
接下来我们再定义一个布局文件,给它取名为button_layout.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" >
</Button>
在 MainActivity 添加 代码
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
LayoutInflater layoutInflater = LayoutInflater.from(this);
View inflate = layoutInflater.inflate(R.layout.button_layout, null);
linearLayout.addView(inflate);
LayoutInflater 技术广泛用于需要动态添加 View 的时候, 比如在 ScrollView 和 ListView 中, 经常都可以看 到 LayoutInflater 的身影。
剖析源码
看一下 LayoutInflater 到底是如何工作的。
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
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, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
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 against its context.
rInflateChildren(parser, temp, attrs, 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 (Exception 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;
}
}