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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章