最近有一關于串列元素鎖定吸頂的需求,處理方案比較簡單的,在外層布局添加一個相同的標題欄控制元件,根據控制元件在滾動過中的位置來判斷顯示隱藏,從而達到效果,使用的關鍵代碼是:
int[] loc = new int[2]; view.getLocationOnScreen(loc); int[] fitLoc = new int[2]; outView.getLocationOnScreen(fitLoc); if (loc[1] <= fitLoc[1]){ //外部標題欄顯示 }else{ //外部標題欄隱藏 }
在這個程序中,碰到幾個問題:
1、當資料比較多,超過一個屏時,屏下所要固定的標題欄,顯示狀態時InVisible的狀態,且所在螢屏位置坐標為(0, 0),這會導致顯示判斷的錯誤,這一情況做過濾處理;
2、當資料量從多到少或從少到多變化時,外層標題欄都要默認隱藏,串列標題欄都要默認顯示(在onBindViewHolder()寫);
以上如果是針對子項某一元素吸頂就夠了,如果是對多個子元素需要吸頂需加如下處理:
1、串列的資料結構使用Map<TitleBean, List<ContentBean>>,的鍵值對, 重寫的adapter的getItemCount()t,用TitleBean+ItemBean作為總數,這時我們可以建立演算法(計算Map與List一一對應的物件),如果界面展示的是九宮格布局GridLayoutManager的方式,可以重寫onAttachedToRecyclerView進行一維串列化,(關于公有/私有修飾,大家隨意 )
private Map<TitleBean, List<ContentBean<T>>> data = https://www.cnblogs.com/xiaofei100/archive/2023/03/03/new TreeMap<>(); @Override public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof GridLayoutManager) { final GridLayoutManager gridManager = ((GridLayoutManager) manager); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return getItemViewType(position) != Type.Content ? gridManager.getSpanCount() : 1; } }); } } private BaseTimeBean<T> getItemBean(int pos){ if(data.isEmpty()) return null; int count = 0; for(TimeBean titleBean : data.keySet()){ count++; if (count -1 == pos) return titleBean; else { List<ImageBean<T>> contentBeans = data.get(titleBean); if (count + contentBeans.size() -1 <= pos){ int index = pos-count; return (index >= 0 && index < contentBeans.size()) ? contentBeans.get(pos- count) : null; }else { count += contentBeans.size(); } } } return null; } public class ItemBean<T>{ public String id; public String name; public T t; } public class TimeBean extends ItemBaen{} public class ContentBean<T> extends ItemBean<T>{}
2、添加串列控制元件的滑動監聽了,如addOnScrollListener,重寫onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy)方法,用布局管理器找第一個可是元素位置findFirstVisibleItemPosition,傳入getTitleBean方法中,找打對應的資料, 進而賦值到吸頂控制元件上,
private TitleBean getTitleBean(int pos){ if(data.isEmpty()) return null; int count = 0; for(TitleBean titleBean : data.keySet()){ count++; if (count -1 == pos) return titleBean; else { int size = data.get(titleBean).size(); if (count + size -1 <= pos){ int index = pos-count; return titleBean; }else { count += size; } } } return null; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/545784.html
標籤:其他
