LayoutInflater使用
- LayoutInflater layoutInflater = LayoutInflater.from(context);
- LayoutInflater layoutInflater = mActivity.getLayoutInflater();
- LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第一种,第二种内部实现都是通过调用第三种
layoutInflater.inflate(R.layout.ResourceID, null);
根View设置的width,height参数不会生效。所以很多dialog,toast setView是自适应大小的 而view是通过inflate而来的,虽然view设置为match_parent 还是固定大小 但仍然显示为wrap_content自适应大小的原因。
源码解析
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
表示如果root参数为null,那么attachToRoot默认为false
不管你是使用的哪个inflate()方法的重载,最终都会辗转调用到LayoutInflater的如下代码中:
LayoutInflater其实就是使用Android提供的pull解析方式来解析布局文件的。
它是用于根据节点名来创建View对象的。确实如此,在createViewFromTag()方法的内部又会去调用createView()方法,然后使用反射的方式创建出View的实例并返回。
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;
// 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
// 这里通过createViewFromTag加载了当前xml资源的根view
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
// 如果root不等于null
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " + root);
}
// Create layout params that match root, if supplied
// 说明此时根view的LayoutParams可以通过xml属性值来获取,也就是说此时在跟view中设置的layout_width,layout_height是会生效的
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
// 如果此时attachToRoot为false,那么表示返回根view而不是root,同时view中设置的layout_width,layout_height是会生效的
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
// 这里循环装载根View下的子view
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.
// 只有当root != null &&
// attachToRoot同时满足的时候才返回root。同时把根View添加到root中,LayoutParams参数
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.
// 返回根View
if (root == null || !attachToRoot) {
result = temp;
}
}
return result;
}
}
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
public LayoutParams(Context c, AttributeSet attrs) {
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
setBaseAttributes(a,
R.styleable.ViewGroup_Layout_layout_width,
R.styleable.ViewGroup_Layout_layout_height);
a.recycle();
}
void rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate)
throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
// 装载当前节点的view
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
// 设置该view的LayoutParams参数
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 递归装载子view
rInflateChildren(parser, view, attrs, true);
// 把该view添加到viewGroup中
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
总结一下:
1. inflate方法返回root还是xml根view,由root和attachToRoot决定
2. 同时xml根View是否具有LayoutParams参数,也是由root和attachToRoot决定。同时如果root不为null,但是attachToRoot为false,那么只设置了该根View的LayoutParams参数,但是返回的仍然是根View
3. 通过pull解析xml的方式递归解析子节点,由代码可以看出子节点始终具有LayoutParams参数
inflate重载方法举例
主界面activity_main.xml
<LinearLayout
android:id="@+id/layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Parent Button"/>
</LinearLayout>
childview_layout.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp"
android:text="Child Button"/>
inflate(resourceId,null)举例
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.layout);
LayoutInflater layoutInflater = LayoutInflater.from(this);
View childLayout = layoutInflater.inflate(R.layout.childview_layout, null);
mainLayout.addView(childLayout);
}
执行结果:此时可以看到ChildButton的大小并不是200dp,而是自适应大小,因为 首先在inflate过程中,因为没有root,所以并没有设置LayoutParams参数。但是在addView
过程中默认执行了LinearLayout的generateDefaultLayoutParams方法,所以该ChildButton的new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);所以是自适应大小,具体这里的分析可以看下文。
另外一种情况:childview_layout.xml修改为如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="2dp"
android:layout_height="1dp"
android:orientation="vertical">
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp"
android:text="Child Button"/>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Child Button2"/>
</LinearLayout>
执行结果:此时根linearlayout的android:layout_width="2dp" android:layout_height="1dp"设置不生效,实际上它的LayoutParams参数被设置为了layout_width和layout_height都为wrap_content。但是ChildButton1和ChildButton2都有linearlayout这个viewgroup,所以他们都设置了LayoutParams,layout_width和layout_height设置生效。最后呈现的结果如下。
inflate(resourceID,root,false)举例
//View childLayout = layoutInflater.inflate(R.layout.childview_layout, null);
View childLayout = layoutInflater.inflate(R.layout.childview_layout, mainLayout, false);
childview_layout.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="200dp"
android:text="Child Button"/>
执行结果如下:此时ChildButton的大小正确的显示成了200dp,为什么呢?因为此时执行到了代码块params = root.generateLayoutParams(attrs);所以该xml根view的LayoutParams被正确的设置为了200dp,同时inflate返回的是该根View,所以最后成功显示。
setContentView重载方法示例
setContentView(resourceID)举例
有些人可能会好奇那么,为什么setContentView(R.layout.activity_main);如果activity_main.xml中设置layout_width,layout_height就会生效呢?
因为setContentView()方法中,Android会自动在布局文件的最外层再嵌套一个FrameLayout,所以layout_width和layout_height属性才会有效果。其实内部调用了inflate方法
可以看看源代码
Activity.java
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
实际上调用了PhoneWindow的setContentView方法
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
mContentParent在installDecor方法中赋值,mContentParent = generateLayout(mDecor); 继续跟踪下去返回的其实是ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
这里其实就是那个framelayout布局,系统自动生成。因为PhoneWindow不公开,但是可以通过http://androidxref.com/6.0.0_r1/自己查看。
mLayoutInflater.inflate(layoutResID, mContentParent);
可以看到所以setContentView中的xml中设置的layout_width和layout_height属性才会有效果。
因为inflate的时候就被正确的加载了LayoutParams
setContentView(View)举例
LayoutInflater layoutInflater = LayoutInflater.from(this);
LinearLayout mainLayout = (LinearLayout) layoutInflater.inflate(R.layout.activity_main, null);
setContentView(mainLayout);
activity_main.xml如下
<LinearLayout
android:id="@+id/layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/darker_gray">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Parent Button"/>
</LinearLayout>
此时执行结果ParentButton充满整个屏幕,为什么呢?
因为PhoneWindow中有
@Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
所以最外面一层,都是MATCH_PARENT的,也就是充满整个屏幕。
总结
不管是inflate还是setContentView的方法的不同重载都只是影响该xml根View是否具有LayoutParam参数,如果没有就是需要使用默认的,如果有就说明xml中设置的layout_width,layout_height生效了。然后View的LayoutParam参数参数进而会影响到view绘制过程中的测量过程。
View childLayout = layoutInflater.inflate(R.layout.childview_layout, null);
mainLayout.addView(childLayout);
此时就算childview_layout的layout_width,layout_height参数被设置为了300dp,300dp。但是childview_layout的LayoutParam仍然是wrap_content,wrap_content。
LayoutParam参数在如下地方被使用,ViewGroup测量所有子view的时候,会把子view的LayoutParam参数取出来,评估之后传给子view的measure方法
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight, lp.width);//使用了view的LayoutParam参数
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom, lp.height);//使用了view的LayoutParam参数
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
......
}
public static final int MATCH_PARENT = -1;
public static final int WRAP_CONTENT = -2
AddView详解
首先参考 http://www.tuicool.com/articles/2MZBNf
ViewGroup中
public void addView(View child, int index) {
if (child == null) {
throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
}
//首先取得该child view的LayoutParams,该layoutParams其实就是通过setLayoutParams设置的mLayoutParams参数,如果为null,就使用默认的LayoutParams
LayoutParams params = child.getLayoutParams();
if (params == null) {
params = generateDefaultLayoutParams();//生成默认的layoutparams,不同的viewgroup有自己的实现
if (params == null) {
throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
}
}
addView(child, index, params);
}
最后都是调用addViewInner方法
private void addViewInner(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
if (mTransition != null) {
// Don't prevent other add transitions from completing, but cancel remove
// transitions to let them complete the process before we add to the container
mTransition.cancel(LayoutTransition.DISAPPEARING);
}
if (child.getParent() != null) {
throw new IllegalStateException("The specified child already has a parent. " +
"You must call removeView() on the child's parent first.");
}
if (mTransition != null) {
mTransition.addChild(this, child);
}
//如果不是..实例,那么生成默认的layoutparams
if (!checkLayoutParams(params)) {
params = generateLayoutParams(params);
}
if (preventRequestLayout) {
child.mLayoutParams = params;
} else {
child.setLayoutParams(params);
}
……
}
LinearLayout中的实现
@Override
protected LayoutParams generateDefaultLayoutParams() {
if (mOrientation == HORIZONTAL) {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
} else if (mOrientation == VERTICAL) {
return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
return null;
}
可以看到如果该linearlayout是水平布局,那么都是WRAP_CONTENT,如果是垂直布局,那么宽度将是MATCH_PARENT,但高度仍然是WRAP_CONTENT,这个比较有意思,需要特别留意。这就解释了为什么上文中的部分《 inflate(resourceId,null)举例》为什么不管button的layout height和width设置为什么,都是显示自适应大小的问题
参考:
1. Android LayoutInflater原理分析,带你一步步深入了解View(一)
3. addView解惑