Android关于LayoutInflater加载布局导致布局宽高失效

本文探讨了在Android中使用LayoutInflater加载布局时,为何设置的match_parent宽度会失效,转而变为wrap_content的问题。通过源码解析,解释了2个参数和3个参数的LayoutInflater方法的区别,并提供了解决方案。当root不为空且attachToRoot为false时,会为View设置LayoutParams。若RecyclerView发现LayoutParams为空,会赋予默认值,导致现象发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

已停止更新,点击跳往独立博客

为何宽高失效?

想要实现如下效果只需要一个recyclerView里面一个textView即可。
image.png

Adapter 代码

static class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {

        private Context mContext;
        private List<String> mStrings = new ArrayList<>();

        public MyAdapter(Context context) {
            mContext = context;
            for (int i = 0; i < 20; i++) {
                mStrings.add("" + i);
            }
        }

        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
            return new MyHolder(view);
        }

        @Override
        public void onBindViewHolder(MyHolder holder, int position) {
            holder.mTextView.setText(mStrings.get(position));
        }

        @Override
        public int getItemCount() {
            return mStrings.size();
        }

        static class MyHolder extends RecyclerView.ViewHolder {

            TextView mTextView;

            public MyHolder(View itemView) {
                super(itemView);

                mTextView = itemView.findViewById(R.id.text);
            }
        }
    }

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="wrap_content"
    android:background="@android:color/black"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:padding="12dp"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:text="123123"/>
   
</LinearLayout>

可是实现的效果是这样的

image.png

可以看到宽明明是match _ parent但是在这里却变成了wrap_content,即文本长度多长,textView宽度都宽,为什么会失效呢?

首先一个View的宽高padding什么的失我第一个想到的就是LayoutParams,因为一些xml里面属性都在LayoutParams里面,如果失效了估计是LayoutParams没有set上去。


关于LayoutInflater

LayoutInflater.from(mContext).inflate(R.layout.item_list, null);

LayoutInflater.from(mContext).inflate(R.layout.item_list,parent, false);

以上是最为普通使用LayoutInflater加载Layout方式,上面的列子中如果使用了3个参数的方法来加载Layout,也就解决了宽度问题,搞懂了2个参数和3个参数方法的区别也就明白了。

代码如下

@Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
            return new MyHolder(view);
        }

如上也就解决了宽度失效问题,可是为什么呢?

源码

 /**
     * 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);
    }

本质上2个参数的方法也是调用了3个参数的方法。
三个参数源码如下

 /**
     * 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) + ")");
        }
		//解析xml
        final XmlResourceParser parser = res.getLayout(resource);
        try {
        //inflate的地方
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
 /**
     * 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) {
           		... 省略部分代码
           		
                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }
					// 判断是否是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 {

                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
						// 关键点
                    ViewGroup.LayoutParams params = null;
						// parent 是否为空
                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
					       // 创建跟布局的LayoutParams
                        params = root.generateLayoutParams(attrs);
							// 是否为false 如果是flase则添加到view里面
                        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.
                    // 注意到这里如果是true 则会将其View添加到root里面
                    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;
                    }
                }
				          ... 省略部分代码
            return result;
        }
    }

注意看到判断是否MERGE的else分支,里面关键的地方都已经写上注释。

其实也就是说,如果root不是空的话,回去创建LayoutParams,在判断如果attchToRoot参数如果是false,则会setLayoutParams到View里面去。

文章的开头有说到LayoutParams这个类,里面都是一个在xml声明的属性,那我们尝试的从侧门解决一下问题,看如下代码

@Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
            view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new MyHolder(view);
        }

我手动为其设置了LayoutParams,结果如何呢?如下

image.png

一样的。

为什么失效之后又是wrap_content呢?

这是因为RecyclerView里面机制如果LayoutParams是空的会给一个默认的LayoutParams。以后有兴趣贴源码。

总结

// 只会生成View 并不会设置任何属性
LayoutInflater.from(mContext).inflate(R.layout.item_list, null);
// 如果parent不为空会为其生成LayoutParams属性,
// attchToRoot如果为flase则会将LayoutParams Set进去,如果为true,则会添加到root里面
LayoutInflater.from(mContext).inflate(R.layout.item_list,parent, false);

分割线

这种问题其实在开发中非常常见不过当时解决了之后并没有深究其原因实属不该。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值