RecyclerView的列表布局中match_parent失效的解决方法

今天在学习RecyclerView的列表布局中发现了一个很头疼的问题:我给列表中的item设置的布局的宽度明明是match_parent,可是呈现出来的效果却是wrap_content,也就是每个item的宽度都没有填充屏幕。

在onCreateViewHolder方法中,我填充item的布局是这样写的:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = View.inflate(context, R.layout.item_recyclerview, null);
    }

但在网上查了一下,有人建议采用下面的写法:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//        View itemView = View.inflate(context, R.layout.item_recyclerview, null);
        LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.item_recyclerview,parent,true);
        return new ViewHolder(itemView);
    }

这个写法添加了parent参数,但是运行之后却报出下面的错:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.

说明我们要填充的View已经有了一个父View,必须从父View中移除才能使用,对这个错误我也不是很理解,但是这个bug还是没有解决,继续寻找方法,最后试了下面这一种,可以了:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.item_recyclerview,null,true);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        itemView.setLayoutParams(lp);
        return new ViewHolder(itemView);
    }

这里的写法的意思item作为子布局,向父布局RecyclerView传递了自己需要的布局数据,则宽是match_parent,高是wrap_content。运行之后,发现match_parent终于发挥作用了。

参考文章:http://blog.csdn.net/ll530304349/article/details/52605202

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值