RecyclerView控件列表项布局match_parent属性失效的根本原理

之前用RecyclerView为了达到自己想要的结果,把item的根布局(最外层Layout)的大小设为match_parent,一开始却发现一个很大的问题!咦?为什么我的item一加载就成了wrap_content的效果?我的match_parent为什么效果显示不出来…在尝试了很多很多方法觉得应该不是我写错了之后,我才意识到我根本不知道LayoutInflater的inflate这个函数的参数的意义,查了api还是不解,这个第三个参数attachToRoot到底是啥意思?为了弄懂这个问题,看了很多博客,觉得这个是个好问题!弄懂了它,你再也不会错误的用inflate了!

我们最常用的便是LayoutInflater的inflate方法,这个方法重载了四种调用方式,分别为:

1. public View inflate(int resource, ViewGroup root)

2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)

3.public View inflate(XmlPullParser parser, ViewGroup root)

4.public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

而我们最常用的用法就是这样(RecyclerView的Adapter中):

@Override
    public AgendaDetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_agenda_detail, null);
        AgendaDetailHolder holder = new AgendaDetailHolder(view);
        return holder;
    }

看似很简单的一个调用,原来有四个重载,而我们最简单的用法就是上面这段用法,也是我一开始的用法(复制粘贴就是这样,你也不会去看细节)

可当你运行测试的时候,你惊讶的发现,说好的效果呢?

下面是我item的布局文件,清清楚楚的写着match_parent

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="match_parent"
        android:layout_height="50dp">
    </View>
    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/id_agenda_detail_layout"
        android:background="#afbfff"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <LinearLayout
            android:background="#FFFFFF"
            android:orientat
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值