1. 程式人生 > >StaggeredGridLayoutManager瀑布流錯亂和頂部空白問題解決

StaggeredGridLayoutManager瀑布流錯亂和頂部空白問題解決

遇到這個問題,去網上搜索的答案一般是:

staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
然後在onScrollStateChanged方法裡:
staggeredGridLayoutManager.invalidateSpanAssignments();
但是,這樣做之後還是會有item錯亂的問題,這種做法是在滑動停止的時候重新requestLayout一下而已,invalidateSpanAssignments()原始碼如下:
/**
 * For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items.
* <p> * If you need to cancel current assignments, you can call this method which will clear all * assignments and request a new layout. */ public void invalidateSpanAssignments() { mLazySpanLookup.clear(); requestLayout(); }
可以看出,此方法並不能從根本上解決錯亂的問題,要解決此問題,還需從原因下手。

為什麼會出現空白和錯亂現象?

空白和錯亂本質上是同一個原因造成的。是因為recyclerview的複用機制遇上圖片非同步載入造成的,當瀑布流需要載入的圖片的高度不一致時,假設第一個離開屏幕後的item的圖片高度是100,被回收,而下一個要進入螢幕的item的圖片高度是80,當圖片還沒載入完,下個item複用了第一個離開螢幕的item,產生了20的高度差,所以會出現錯亂的現象,表現為圖片展示區域與圖片不匹配,要避免錯亂,需要從item的高度控制入手

解決方案:

在onBind方法中,必須在圖片載入方法之前設定圖片高度:

ViewGroup.LayoutParams imageLayoutParams = imageViewHolder.image.getLayoutParams();
imageLayoutParams.width = CommonUtil.getDMWidthPixels(mContext) / 2;//獲取實際展示的圖片寬度
imageLayoutParams.height = (int) (imageLayoutParams.width * density);//獲取最終圖片高度
imageViewHolder.image.setLayoutParams(imageLayoutParams);
//應用高度到佈局中
這樣,在每次onbind方法剛開始執行,圖片沒加載出來之前,先給圖片預留出來一定的高度,使每個item的高度固定,就不會再出現item錯亂的問題