【我的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
☞ oypcz@foxmail.com


发布了469 篇原创文章 · 获赞 1452 · 访问量 355万+
展开阅读全文

报错view.InflateException: Binary XML file line

11-20

比较老的项目,主界页面使用的TabActivity切换,在首页的viewpager中的fragment的布局文件中报错,布局文件报错为一个TextView,样式很简单,但是报错,尝试将该TextView注释后,依然报错,显示为首页的另一个控件,感觉和项目配置有关,目前仍然找不到错误,在华为Mate10上打开直接关闭,在荣耀v8和mate9pro上可以正常打开,以下是报错日志,求大神指点 android.view.InflateException: Binary XML file line #22: Binary XML file line #22: Error inflating class android.widget.TextView Caused by: android.view.InflateException: Binary XML file line #22: Error inflating class android.widget.TextView Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance0(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:334) at android.view.LayoutInflater.createView(LayoutInflater.java:647) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.rInflate(LayoutInflater.java:866) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.rInflate(LayoutInflater.java:866) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at com.tidemedia.nntv.sliding.fragment.TuijianFragment.onCreateView(TuijianFragment.java:134) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149) at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103) at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984) at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) at android.support.v4.view.ViewPager.populate(ViewPager.java:1268) at android.support.v4.view.ViewPager.populate(ViewPager.java:1116) at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642) at android.view.View.measure(View.java:21998) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) at android.view.View.measure(View.java:21998) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:21998) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:21998) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:21998) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at com.android.internal.policy.DecorView.onMeasure(DecorView.java:721) at android.view.View.measure(View.java:21998) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) 以下是xml布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="180dp"> <android.support.v4.view.ViewPager android:id="@+id/newsGallery" android:layout_width="match_parent" android:layout_height="180dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="30dp" android:layout_alignParentBottom="true" android:background="#64000000"> <android.widget.TextView android:id="@+id/viewpager_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:lines="1" android:textColor="@color/white" android:textSize="15sp" /> </RelativeLayout> 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览