在使用recyclerView結合StaggeredGridLayoutManager實現瀑布流時遇到item間隔不一致的問題。
我的問題出現在onCreateViewHolder中,在創建ViewHolder時,使用的inflate方法造成的。
inflate方法有兩種形式,一個是兩個參數
/** * Inflate a new view hierarchy from the specified xml resource. Throws * {@link InflateException} if there is an error. * * @param resource ID for an XML layout resource to load (e.g., * <code>R.layout.main_page</code>) * @param root Optional view to be the parent of the generated hierarchy. * @return The root View of the inflated hierarchy. If root was supplied, * this is the root View; otherwise it is the root of the inflated * XML file. */ public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); }
一個是三個參數的
/** * Inflate a new view hierarchy from the specified xml resource. Throws * {@link InflateException} if there is an error. * * @param resource ID for an XML layout resource to load (e.g., * <code>R.layout.main_page</code>) * @param root Optional view to be the parent of the generated hierarchy (if * <em>attachToRoot</em> is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if <em>attachToRoot</em> is false.) * @param 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. * @return 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. */ public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { final Resources res = getContext().getResources(); if (DEBUG) { Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" (" + Integer.toHexString(resource) + ")"); } final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { parser.close(); } }
這兩個inflate都共有一個參數 root 參數,
root:需要附加到resource資源文件的根控件,什麼意思呢,就是inflate()會返回一個View對象,
如果第三個參數attachToRoot爲true,
就將這個root作爲根對象返回,
否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根佈局對象上,
也就是佈局文件resource的最外層的View上,比如是一個LinearLayout或者其它的Layout對象
如果root不爲空的話,那麼root的LayoutParams屬性會附加到resource對象的根佈局對象上,這就容易導致item 間距不一,所以
在創建ViewHolder的時候第二個參數爲空。
上述如不正確,請指正!