您的位置:首页 > 其它

LayoutInflater简单理解

2016-02-28 23:12 225 查看
在LayoutInflater的学习中有以下体会:

先看几个例子

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);

// Example1 出错
//View trueLayout = LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, true);
//mainLayout.addView(trueLayout);

// Example2 Button的Params无效
//View trueLayout = LayoutInflater.from(this).inflate(R.layout.button_layout,null);
//mainLayout.addView(trueLayout);

// Example3
LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, true);

// Example4
View falseLayout = LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, false);
mainLayout.addView(falseLayout);
}


布局文件如下:

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"
android:orientation="horizontal">
</LinearLayout>


button_layout.xml

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Button">
</Button>


Example1:

会抛出异常

Example2:

Button的宽度没有100dp只是WRAP_CONTNET

Example3:

正常

Example4:正常

原因:

首先进入
LayoutInflater#inflate()
源码看看:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}

final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}


然后进入
inflate(parser, root, attachToRoot);


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
}

//找到xml文档的Start位置
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 {
//重点1:Temp节点是要解析的xml文档的root节点
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
//重点2:parms到底是temp节点还是root的LayoutParams
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
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
// 重点3:当attachToRoot == false 时,调用下面函数
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) {
// 重点4:当attachToRoot == true时,调用下面函数
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;
}
}


解析xml文档采用的PULL方式

区分
root
temp
root
为函数参数
ViewGroup
,
temp
为xml文档的根节点

attachToRoot == true
会调用
root.addView(temp, params);
,所以在一开始的Example1就会出错(不能重复添加啊),Example3就对了。当
attachToRoot == fasle
调用
temp.setLayoutParams(params);
所以在Example4要调用
mainLayout.addView(falseLayout);
不然就看不到
Button
了。

对于
params
变量(我一开始想了好久),
params = root.generateLayoutParams(attrs);
这句代码

/**
* Returns a new set of layout parameters based on the supplied attributes set.
*
* @param attrs the attributes to build the layout parameters from
*
* @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
*         of its descendants
*/
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}


返回一个
LayoutParams
基于给的
AttributeSet
参数,那么
AttributeSet
从哪里来?

final AttributeSet attrs = Xml.asAttributeSet(parser);


parser
为xml文档的
parser
,所以
params
变量为temp的
LayoutParams
(xml文档里面设置啦)。

- 当
attachToRoot == true
inflate()
函数返回
root
;当
attachToRoot == true
inflate()
函数返回
temp


最后说一点:

layout_height
layout_width
不是
View
的真实高度,它是根据
Parent View
与当前
View
决定的。

Example2,里面由于
root
为空,默认
attachToRoot
true
params = root.generateLayoutParams(attrs);
就不会调用,
params
就为空。还有一点就是:
root.addView(temp, params);
不会调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: