在使用RecycleView
的時候,添加item布局文件之后,發現顯示效果并沒有像自己想的那樣“match_parent”,而是
后面的居然顯示不完全。
查了下,發現自己
inflate
的姿勢不對:(我原來這么寫
View view = View.inflate(viewGroup.getContext(), R.layout.activity_row_question, null);
)
The docs for inflate:
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.
Parameters
resource ID for an XML layout resource to load (e.g., R.layout.main_page) root view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
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. Returns 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.
It is important here to not supply true, but do supply the parent:
LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_listitem, parent, false);
(英文不太好,上面看不太懂(⊙﹏⊙)b)后來,我又在網上找到了郭霖大神的一篇文章:Android LayoutInflater原理分析,帶你一步步深入了解View(一),里面有這么一段:
比較細心的朋友也許會注意到,inflate()方法還有個接收三個參數的方法重載,結構如下:
inflate(int resource, ViewGroup root, boolean attachToRoot)
那么這第三個參數attachToRoot又是什么意思呢?其實如果你仔細去閱讀上面的源碼應該可以自己分析出答案,這里我先將結論說一下吧,感興趣的朋友可以再閱讀一下源碼,校驗我的結論是否正確。
- 如果root為null,attachToRoot將失去作用,設置任何值都沒有意義。
- 如果root不為null,attachToRoot設為true,則會給加載的布局文件的指定一個父布局,即root。
- 如果root不為null,attachToRoot設為false,則會將布局文件最外層的所有layout屬性進行設置,當該view被添加到父view當中時,這些layout屬性會自動生效。
- 在不設置attachToRoot參數的情況下,如果root不為null,attachToRoot參數默認為true。