要看结论直接拉到底部
在用代码inflate一个XML布局文件添加到父容器时,偶尔会碰到这个inflate出来的view,会无法正确显示我们在xml中所定义的样子,比如可能会无法正确显示最外层定义的参数,width,height,padding,margin等等。今天研究了下inflate的源码,总算明白了正确使用的姿势。
inflate一个xml布局文件有多种方式:比如可以调用View类的inflate方法,
public static View inflate (Context context, int resource, ViewGroup root)
还可以调用LayoutInflater.from(context).inflate,但其实第一种方法最后也是调用LayoutInflater.from(context).inflate
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
所以我们只要分析public View inflate (int resource, ViewGroup root, boolean 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 last