【我的Android进阶之旅】解决一次由于LayoutInflater中inflate方法调用不当导致的item的宽高显示不正常的问题

一、问题描述

最近APP进行大改版,整体UI风格都改变了。因此全部包含Banner的界面都需要调整 UI。 在替换过程中,有一个界面的UI出现了问题。

  • UI设计人员要求的实现效果

在这里插入图片描述

  • 实现出现问题的效果

在这里插入图片描述

绿色的背景完全显示不出来,导致界面及其难看。

整个Banner控件高度和banner图片资源的高度一样,完全没有背景的空间。

在这里插入图片描述
在这里插入图片描述

二、分析问题

2.1 使用Layout Inspector 工具分析问题

  • 错误的
    使用Layout Inspector 工具,看看发现这个背景的高度是1px

在这里插入图片描述

  • 正常的
    使用Layout Inspector 工具,看解决问题之后正常显示的UI 背景高度是585px

在这里插入图片描述

  • watchset_authorize_head_view.xml 布局文件
    可以看出来,预览的布局文件是对的,没有问题的。

在这里插入图片描述

而且除了这一个界面不对之外,其他的20多个界面的Banner都是类似的代码,完全没有问题。 因此我怀疑完全不是xml布局导致的问题,而是业务代码添加这个 watchset_authorize_head_view.xml 布局文件出现了问题。

2.2 分析业务代码加载 watchset_authorize_head_view.xml 布局文件的问题

  • 错误的加载方式
    在这里插入图片描述
 View headView = View.inflate(this, R.layout.watchset_authorize_head_view, null);
 listView.addHeaderView(headView, null, false);

2.3 修复问题

将上面的代码改成下面的加载方式,即可修复该问题。
在这里插入图片描述

View headView = LayoutInflater.from(this)
                    .inflate(R.layout.watchset_authorize_head_view, listView,false);
listView.addHeaderView(headView, null, false);

2.4 解析android.view.LayoutInflater#inflate(int, android.view.ViewGroup)

上面的android.view.View#inflate(Context context, @LayoutRes int resource, ViewGroup root) 方法
最终还是调用了android.view.LayoutInflater#inflate(@LayoutRes int resource, @Nullable ViewGroup root) 方法,如下所示
在这里插入图片描述

 /**
     * Inflate a view from an XML resource.  This convenience method wraps the {@link
     * LayoutInflater} class, which provides a full range of options for view inflation.
     *
     * @param context The Context object for your activity or application.
     * @param resource The resource ID to inflate
     * @param root A view group that will be the parent.  Used to properly inflate the
     * layout_* parameters.
     * @see LayoutInflater
     */
    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

android.view.LayoutInflater#inflate(@LayoutRes int resource, @Nullable ViewGroup root) 方法的源代码如下所示

 /**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

在这里插入图片描述

继续调用 android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean) 方法

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> 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(@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();
        }
    }

在这里插入图片描述
继续调用 android.view.LayoutInflater#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) 方法

 /**
     * Inflate a new view hierarchy from the specified XML node. Throws
     * {@link InflateException} if there is an error.
     * <p>
     * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;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
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> 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;
            //定义返回值,初始化为传入的形参root
            View result = root;

            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                //如果一开始就是END_DOCUMENT,那说明xml文件有问题
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
                //有了上面判断说明这里type一定是START_TAG,也就是xml文件里的root node
                final String name = parser.getName();

                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }
                //处理merge tag的情况(merge,你懂的,APP的xml性能优化)
                //root必须非空且attachToRoot为true,否则抛异常结束(APP使用merge时要注意的地方,
                //因为merge的xml并不代表某个具体的view,只是将它包起来的其他xml的内容加到某个上层ViewGroup中。
                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");
                    }
                    //递归inflate方法调运
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    //xml文件中的root view,根据tag节点创建view对象
                    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
                        //根据root生成合适的LayoutParams实例
                        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的setLayoutParams方法
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // Inflate all children under temp against its context.
                     //递归inflate剩下的children
                    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非空且attachToRoot=true则将xml文件的root view加到形参提供的root里
                        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) {
                        //返回xml里解析的root view
                        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);
            }
            //返回参数root或xml文件里的root view
            return result;
        }
    }

从上面的源码分析我们可以看出inflate方法的参数含义:

  • inflate(xmlId, null); 只创建temp的View,然后直接返回temp。

  • inflate(xmlId, parent); 创建temp的View,然后执行root.addView(temp, params);最后返回root。

  • inflate(xmlId, parent, false); 创建temp的View,然后执行temp.setLayoutParams(params);然后再返回temp。

  • inflate(xmlId, parent, true); 创建temp的View,然后执行root.addView(temp, params);最后返回root。

  • inflate(xmlId, null, false); 只创建temp的View,然后直接返回temp。

  • inflate(xmlId, null, true); 只创建temp的View,然后直接返回temp。


上面的
android.view.LayoutInflater#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean)
方法调用了
android.view.LayoutInflater#rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate) 方法

  • android.view.LayoutInflater#rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate) 的代码如下所示
    /**
     * Recursive method used to descend down the xml hierarchy and instantiate
     * views, instantiate their children, and then call onFinishInflate().
     * <p>
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * override it.
     */
 void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
            boolean finishInflate, boolean inheritContext) throws XmlPullParserException,
            IOException {

        final int depth = parser.getDepth();
        int type;
        //XmlPullParser解析器的标准解析模式
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            //找到START_TAG节点程序才继续执行这个判断语句之后的逻辑
            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            //获取Name标记
            final String name = parser.getName();
            //处理REQUEST_FOCUS的标记
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                //处理tag标记
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                //处理include标记
                if (parser.getDepth() == 0) {
                    //include节点如果是根节点就抛异常
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, parent, attrs, inheritContext);
            } else if (TAG_MERGE.equals(name)) {
                //merge节点必须是xml文件里的根节点(这里不该再出现merge节点)
                throw new InflateException("<merge /> must be the root element");
            } else {
                //其他自定义节点
                final View view = createViewFromTag(parent, name, attrs, inheritContext);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true, true);
                viewGroup.addView(view, params);
            }
        }
        //parent的所有子节点都inflate完毕的时候回onFinishInflate方法
        if (finishInflate) parent.onFinishInflate();
    }

2.5 错误原因

所以会出现上面的异常显示的原因是:

  • inflate(xmlId, null)不能正确处理我们设置的宽和高是因为layout_width,layout_height是相对了父级设置的,而此temp的getLayoutParams为null。

  • inflate(xmlId, parent)能正确显示我们设置的宽高是因为我们的View在设置setLayoutParams时params = root.generateLayoutParams(attrs)不为空。

  • inflate(xmlId, parent,false ) 可以正确处理,因为temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);得到的。

  • inflate(xmlId, null, true)与inflate(xmlId, null, false)不能正确处理我们设置的宽和高是因为layout_width,layout_height是相对了父级设置的,而此temp的getLayoutParams为null。


  • 错误代码
View headView = View.inflate(this, R.layout.watchset_authorize_head_view, null);
listView.addHeaderView(headView, null, false);

调用了
android.view.LayoutInflater#inflate(int, android.view.ViewGroup)方法

并且root为空,所以不能正确处理我们设置的宽和高是因为layout_width,layout_height是相对了父级设置的,而此temp的getLayoutParams为null。

因此整个自定义的Banner,除了那种图片是可以显示之外,背景和Banner View的高度完全靠那张图片撑着。

  • 正确代码
View headView = LayoutInflater.from(this)
                        .inflate(R.layout.watchset_authorize_head_view, listView,false);
listView.addHeaderView(headView, null, false);

改成正确代码之后,调用的是inflate(xmlId, parent,false ) 可以正确处理,因为temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);得到的。

所以可以将整个Banner的高度显示出来。

  • 为什么之前的Banner UI风格可以正常显示呢?

因为这代码之前的整个Banner是靠三张图片叠起来的,背景图也是png图片正好有高度撑起来了。而改版之后的Banner,只有一个内容是png图片,背景图都是使用shape图来实现的,所以不使用正确的inflate方法的话,就撑不起来。

三、参考链接

更多详细讲解可以参考下面的链接,了解更多关于android.view.LayoutInflater#inflate()方法的分析,当然最好的还是自己看懂源代码。

  • https://blog.csdn.net/yanbober/article/details/45970721
    在这里插入图片描述
  • https://blog.csdn.net/u012702547/article/details/52628453

在这里插入图片描述

  • https://www.cnblogs.com/ganchuanpu/p/6533569.html
  • https://blog.csdn.net/lmj623565791/article/details/38171465

作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:https://blog.csdn.net/qq446282412/article/details/99341168
☞ 本人QQ: 3024665621
☞ QQ交流群: 123133153
☞ github.com/ouyangpeng
[email protected]


发布了469 篇原创文章 · 获赞 1467 · 访问量 359万+

猜你喜欢

转载自blog.csdn.net/qq446282412/article/details/99341168