LayoutInflater.inflate未指定父容器导致宽高失效的原因和解决方案

LayoutInflater.inflate我们经常用于加载View,比如:RecyclerView/ListView的item加载、Fragment.onCreateView、Dialog和PopupWindow setContextView等,有些时候我们明明设置了宽高,最后在显示时却没有效果

案例
RecyclerView,加载item

item布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="40dp">

    <TextView
        android:id="@+id/fill_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="填充的邮箱"
        android:textSize="15sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

编译器缩略图应该是:


image.png

实际显示时:


image.png

设置的高度没有起到作用
原因

LayoutInflater.inflate未指定父布局导致LayoutParams缺失,也就是没有指定父布局就没有去读取item顶层设置的宽高。可以使用LayoutInflater.inflate加载View时让第二个参数为空,然后getLayoutParams()这个时候获取到的值为空

为什么会为空?跟踪哈LayoutInflater.inflate

 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 {
                //merge标签
                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 {
                    // 加载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);
                        }
                        // 父布局去创建一个LayoutParams 
                        params = root.generateLayoutParams(attrs);
                        //如果不把view添加到父view,就设置LayoutParams
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    //递归加载子View
                    rInflateChildren(parser, temp, attrs, true);
                    //父view不为空,而且需要添加到父view
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                    //父view为空,或者不添加到父view,就把当前加载view赋值给返回值
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                ...
            }
            return result;
        }
    }

加载逻辑

  1. 无父View的情况下,直接加载View并返回,最后放回的是当前加载的VIew
  2. 有父View的情况下,加载View后,调用父View的generateLayoutParams方法加载LayoutParams,如果不想把View添加到父View就设置LayoutParams,最后放回的是当前加载的VIew
  3. 有父View并且要把加载视图添加进去,就会调用父View的addView方法,最后返回的是父View

到这里就已经理清楚为什么没有设置父View,就会导致LayoutParams缺失。其实就是父View不明确的情况下,没法去确定子View的属性,所以这里的LayoutParams为空,那后续的加载不会出错?

没有LayoutParams的Item,RecyclerView是如何去处理布局的

RecyclerView.tryGetViewHolderForPositionByDeadline

RecyclerView.ViewHolder tryGetViewHolderForPositionByDeadline(int position, boolean dryRun, long deadlineNs) {
                ...
                android.view.ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                RecyclerView.LayoutParams rvLayoutParams;
                if (lp == null) {
                    rvLayoutParams = (RecyclerView.LayoutParams)RecyclerView.this.generateDefaultLayoutParams();
                    holder.itemView.setLayoutParams(rvLayoutParams);
                }
            ...

这里如果没有设置LayoutParams就使用LayoutManager.generateDefaultLayoutParams去创建一个默认的LayoutParams,我们在xml布局中设置的宽高就失效了。

如何处理?

1. 添加父View

  • **在LayoutInflater.inflate时设置父View
  • 在item布局中在添加一个父View,例如:上面的Item外层在添加ConstraintLayout

2. 添加LayoutParams

  • 在LayoutInflater.inflate加载出View后,调用setLayoutParams
总结
控件 表述
PopupWindow 布局中xml root节点设置宽高失效, 如果创建时未传入宽高,默认宽高为0,不会显示。宽高设置为自适应时,会使用测量的宽高测量内层view所占用的空间
RecyclerView 布局中xml root节点设置宽高失效,设置父View或者设置LayoutParams或者在LayoutManager中重写generateDefaultLayoutParams(不建议使用)
Dialog 布局中xml root节点设置宽高失效, setContentView时未传入参数LayoutParams,者PhoneWindow.setContentView中会创建一个全屏的LayoutParams。传入LayoutParams时使用传入的参数作为root的LayoutParams。
Fragment 布局中xml root节点设置宽高失效, 他的LayoutParams受父布局影响,也就是FragmentTransaction add和replace 中IdRes对应的控件。使用父布局默认的generateDefaultLayoutParams创建LayoutParams
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容