LayoutInflater加载布局遇到的坑

问题:

Fragment,adapter中的视图都是需要LayoutInflater将XML文件转换为View对象,但是使用过程中发现加载后,RecyclerView中item设置宽高以及margin无效

案例:

layout_footer.xml



    

        ...

    

在Activity中加载footer

 View footerView = LayoutInflater.from(mContext).inflate(R.layout.layout_footer,null);

发现上面设置的android:layout_margin=“10”无效

解决:

在布局转换的时候使用

View view = layoutinflater.inflate(R.layout.XXX,ViewGroup,false);

分析:

为什么使用三个参数的inflate方法就能实现效果?

inflate有重载4个方法

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)

public View inflate(XmlPullParser parser, @Nullable ViewGroup root)

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 

最终都会走到

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

 LayoutInflater类中的inflate源码

  /**
     * Inflate a new view hierarchy from the specified XML node. Throws
     * {@link InflateException} if there is an error.
     * 

* Important   For performance * reasons, view inflation relies heavily on pre-processing of XML files * that is done at build time. Therefore, it is not currently possible to * use LayoutInflater with an XmlPullParser over a plain XML file at runtime. * * @param parser XML dom node containing the description of the view * hierarchy. * @param root Optional view to be the parent of the generated hierarchy (if * attachToRoot is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if attachToRoot is false.) * @param attachToRoot Whether the inflated hierarchy should be attached to * the root parameter? If false, root is only used to create the * correct subclass of LayoutParams for the root view in the XML. * @return The root View of the inflated hierarchy. If root was supplied and * attachToRoot is true, this is root; otherwise it is the root of * the inflated XML file. */ 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(" 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) { final InflateException ie = new InflateException(e.getMessage(), e); ie.setStackTrace(EMPTY_STACK_TRACE); throw ie; } catch (Exception e) { final InflateException ie = new InflateException(parser.getPositionDescription() + ": " + e.getMessage(), e); ie.setStackTrace(EMPTY_STACK_TRACE); throw ie; } finally { // Don't retain static reference on context. mConstructorArgs[0] = lastContext; mConstructorArgs[1] = null; Trace.traceEnd(Trace.TRACE_TAG_VIEW); } return result; } }

1)第一个参数XmlPullParser parser

parser:xml文件
如果传入的是layout的id,会调用
final XmlResourceParser parser = res.getLayout(resource);转换成xml文件

2)第二个参数root,第三个参数attachToRoot

root不为空
和第三个参数attachToRoot有关
① 如果attachToRoot为true
root成为inflate出来的view对象的父布局
② 如果attachToRoot为false
inflate出来的view的根布局提供LayoutParams参数的控件

当root不为空,attachToRoot为false时候。
获得xml文件中的属性
通过createViewFromTag生成View
再通过generateLayoutParams(attrs)生成layoutparams参数
设置到view中,使得view有layoutParams

 root为空(null)
不指定父布局,那么inflate出来的view对象的根布局的某些参数会失效,比如layout_width和layout_height,layout_margin会失效


 

你可能感兴趣的:(Android:应用篇,android)