天天看點

RecyclerView條目不能填充的問題

RecyclerView的Item條目不能填充的問題

問題描述:

RecyclerView條目不能填充的問題

發現問題是是用這種方式去填充布局不能填充recyclerview,這個時候Item的根布局是LinearLayout:

View childView = mLayoutInflater.inflate(R.layout.item_member_integral_explain, null,false);
           

方案1.

這個時候保持填充的代碼不變化,去修改根布局為RelativeLayout發現可以填充。

方案2.

View childView = mLayoutInflater.inflate(R.layout.item_member_integral_explain, parent,false);//修改填充代碼為parent
           

這樣也是可以填充滿的,網上多數說的都是該方案。

源碼部分:

// Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);//這裡是拿到Item的rootview。

                    ViewGroup.LayoutParams params = null;
                //這裡是需要看我們是否傳入了root,如果沒有傳入的話下面都不會走了,直接傳回了這個item的根view了
                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);//擷取根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. 
                  //将我們的item加入到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.
                    //直接把我們的Item的view傳回了。
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                return result;
           

上面是填充Item的部分,如果我們傳入的inflate方法第二個參數是null的話其實是沒有給temp設定參數的,而是直接把temp指派給了result并傳回。

推測結論:

方案1能解決該問題,應該是LinearLayout和RelativeLayout兩個view的不同特性導緻,這裡需要去了解兩個view的差別了。

方案2解決問題,是因為對item的根view進行了設定,是以跟view的參數是已經生效了,是以在加入到root上的時候就保持了我們自己設定的屬性。

結束語

希望了解這塊的同學能提供一些完成的解答。

繼續閱讀