在使用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的时候第二个参数为空。
上述如不正确,请指正!