版權聲明:本文爲博主原創文章,未經博主容許不得轉載java
系列教程:Android開發之從零開始系列android
源碼:AnliaLee/android-RecyclerViews,歡迎stargit
你們要是看到有錯誤的地方或者有啥好的建議,歡迎留言評論github
最近項目中要實現列表分組和粘性頭部的效果,網上翻了不少資料和開源庫,感受都不是太好用,有的擴展性不強有的用起來又太複雜,因而決定本身動手造輪子。行動以前,研究了許多前人的源碼,決定了幾點開發方向canvas
目前GroupItemDecoration第一階段已開發完成(會繼續更新和擴展功能),源碼及示例已上傳至Github,具體效果如圖數組
GroupItemDecoration目前只支持LinearLayoutManager.VERTICAL類型,使用流程以下緩存
LayoutInflater layoutInflater = LayoutInflater.from(this);
View groupView = layoutInflater.inflate(R.layout.item_group,null);
複製代碼
recyclerView.addItemDecoration(new GroupItemDecoration(this,groupView,new GroupItemDecoration.DecorationCallback() {
@Override
public void setGroup(List<GroupItem> groupList) {
//設置分組,GroupItem(int startPosition),例如:
GroupItem groupItem = new GroupItem(0);
groupItem.setData("name","第1組");
groupList.add(groupItem);
groupItem = new GroupItem(5);
groupItem.setData("name","第2組");
groupList.add(groupItem);
}
@Override
public void buildGroupView(View groupView, GroupItem groupItem) {
//構建groupView,經過groupView.findViewById找到內部控件(暫不支持點擊事件等),例如
TextView textName = (TextView) groupView.findViewById(R.id.text_name);
textName.setText(groupItem.getData("name").toString());
}
}));
複製代碼
若是仍是不清楚能夠去看下demoide
在咱們自定義ItemDecoration以前首先得了解ItemDecoration有什麼用,不清楚的能夠看下這兩篇博客佈局
簡單來講,咱們實現分組及粘性頭部效果分三步
咱們按順序一步步講,首先,建立GroupItemDecoration繼承自ItemDecoration,在初始化方法中獲取用戶設置的GroupView,並提供接口給用戶設置分組相關
public class GroupItemDecoration extends RecyclerView.ItemDecoration {
private Context context;
private View groupView;
private DecorationCallback decorationCallback;
public GroupItemDecoration(Context context,View groupView,DecorationCallback decorationCallback) {
this.context = context;
this.groupView = groupView;
this.decorationCallback = decorationCallback;
}
public interface DecorationCallback {
/** * 設置分組 * @param groupList */
void setGroup(List<GroupItem> groupList);
/** * 構建GroupView * @param groupView * @param groupItem */
void buildGroupView(View groupView, GroupItem groupItem);
}
}
複製代碼
而後重寫getItemOffsets方法,根據用戶設置的分組爲GroupView預留位置,其中最主要的是測量出GroupView的寬高和位置。measureView方法中按着View的繪製順序調用View.measure和View.layout,只有先完成了這兩步,才能將View繪製到屏幕上,關於如何測量View你們能夠看下這篇博客Android如何在初始化的時候獲取加載的佈局的寬高。接下來是具體的實現代碼
public class GroupItemDecoration extends RecyclerView.ItemDecoration {
//省略部分代碼...
private List<GroupItem> groupList = new ArrayList<>();//用戶設置的分組列表
private Map<Object,GroupItem> groups = new HashMap<>();//保存startPosition與分組對象的對應關係
private int[] groupPositions;//保存分組startPosition的數組
private int positionIndex;//分組對應的startPosition在groupPositions中的索引
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if(!isLinearAndVertical(parent)){//若RecyclerView類型不是LinearLayoutManager.VERTICAL,跳出(下同)
return;
}
if(isFirst){
measureView(groupView,parent);//繪製View須要先測量View的大小及相應的位置
decorationCallback.setGroup(groupList);//獲取用戶設置的分組列表
if(groupList.size()==0){//若用戶沒有設置分組,跳出(下同)
return;
}
groupPositions = new int[groupList.size()];
positionIndex = 0;
int a = 0;
for(int i=0;i<groupList.size();i++){//保存groupItem與其startPosition的對應關係
int p = groupList.get(i).getStartPosition();
if(groups.get(p)==null){
groups.put(p,groupList.get(i));
groupPositions[a] = p;
a++;
}
}
isFirst = false;
}
int position = parent.getChildAdapterPosition(view);
if(groups.get(position)!=null){
//若RecyclerView中該position對應的childView以前須要繪製groupView,則爲其預留相應的高度空間
outRect.top = groupViewHeight;
}
}
/** * 測量View的大小和位置 * @param view * @param parent */
private void measureView(View view,View parent){
if (view.getLayoutParams() == null) {
view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
parent.getPaddingLeft() + parent.getPaddingRight(), view.getLayoutParams().width);
int childHeight;
if(view.getLayoutParams().height > 0){
childHeight = View.MeasureSpec.makeMeasureSpec(view.getLayoutParams().height, View.MeasureSpec.EXACTLY);
} else {
childHeight = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);//未指定
}
view.measure(childWidth, childHeight);
view.layout(0,0,view.getMeasuredWidth(),view.getMeasuredHeight());
groupViewHeight = view.getMeasuredHeight();
}
/** * 判斷LayoutManager類型,目前GroupItemDecoration僅支持LinearLayoutManager.VERTICAL * @param parent * @return */
private boolean isLinearAndVertical(RecyclerView parent){
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (!(layoutManager instanceof LinearLayoutManager)) {
return false;
}else {
if(((LinearLayoutManager) layoutManager).getOrientation()
!= LinearLayoutManager.VERTICAL){
return false;
}
}
return true;
}
}
複製代碼
在RecyclerView爲GroupView預留了空間後,咱們須要重寫onDraw方法將其繪製出來。爲了保證將全部用戶設置的分組都繪製出來,咱們要遍歷RecyclerView全部的childView,當循環到該childView的position能找到對應的GroupItem時,便在該childView的上方繪製出GroupView(該位置正是以前預留的空間),具體代碼以下
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
if(groupList.size()==0 || !isLinearAndVertical(parent)){
return;
}
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
float left = child.getLeft();
float top = child.getTop();
int position = parent.getChildAdapterPosition(child);
if(groups.get(position)!=null){
c.save();
c.translate(left,top - groupViewHeight);//將畫布起點移動到以前預留空間的左上角
decorationCallback.buildGroupView(groupView,groups.get(position));//經過接口回調得知GroupView內部控件的數據
measureView(groupView,parent);//由於內部控件設置了數據,因此須要從新測量View
groupView.draw(c);
c.restore();
}
}
}
複製代碼
接下來是繪製粘性頭部,由兩部分特效構成
推進特效主要是經過相鄰組GroupView的top位置關係來實現,爲了更好地理解相鄰組的關係及接下來的代碼邏輯,博主簡單介紹一下分組邏輯:
RecyclerView可視範圍(當前屏幕中顯示的)內的分組劃分爲「上一組(pre)」、「當前組(cur)」和「下一組(next)」,這三組的劃分依據以下
具體代碼以下(表達能力有限,實在沒搞明白的童鞋能夠調試一下代碼看看各個判斷分支的跳入時機):
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
if(groupList.size()==0 || !isStickyHeader || !isLinearAndVertical(parent)){
return;
}
int childCount = parent.getChildCount();
Map<Object,Object> map = new HashMap<>();
//遍歷當前可見的childView,找到當前組和下一組並保存其position索引和GroupView的top位置
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
float top = child.getTop();
int position = parent.getChildAdapterPosition(child);
if(groups.get(position)!=null){
positionIndex = searchGroupIndex(groupPositions,position);
if(map.get("cur")==null){
map.put("cur", positionIndex);
map.put("curTop",top);
}else {
if(map.get("next")==null){
map.put("next", positionIndex);
map.put("nextTop",top);
}
}
}
}
c.save();
if(map.get("cur")!=null){//若是當前組不爲空,說明RecyclerView可見部分至少有一個GroupView
indexCache = (int)map.get("cur");
float curTop = (float)map.get("curTop");
if(curTop-groupViewHeight<=0){//保持當前組GroupView一直在頂部
curTop = 0;
}else {
map.put("pre",(int)map.get("cur")-1);
if(curTop - groupViewHeight < groupViewHeight){//判斷與上一組的碰撞,推進當前的頂部GroupView
curTop = curTop - groupViewHeight*2;
}else {
curTop = 0;
}
indexCache = (int)map.get("pre");
}
if(map.get("next")!=null){
float nextTop = (float)map.get("nextTop");
if(nextTop - groupViewHeight < groupViewHeight){//判斷與下一組的碰撞,推進當前的頂部GroupView
curTop = nextTop - groupViewHeight*2;
}
}
c.translate(0,curTop);
if(map.get("pre")!=null){//判斷頂部childView的分組歸屬,繪製對應的GroupView
drawGroupView(c,parent,(int)map.get("pre"));
}else {
drawGroupView(c,parent,(int)map.get("cur"));
}
}else {//不然當前組爲空時,經過以前緩存的索引找到上一個GroupView並繪製到頂部
c.translate(0,0);
drawGroupView(c,parent,indexCache);
}
c.restore();
}
/** * 繪製GroupView * @param canvas * @param parent * @param index */
private void drawGroupView(Canvas canvas,RecyclerView parent,int index){
if(index<0){
return;
}
decorationCallback.buildGroupView(groupView,groups.get(groupPositions[index]));
measureView(groupView,parent);
groupView.draw(canvas);
}
/** * 查詢startPosition對應分組的索引 * @param groupArrays * @param startPosition * @return */
private int searchGroupIndex(int[] groupArrays, int startPosition){
Arrays.sort(groupArrays);
int result = Arrays.binarySearch(groupArrays,startPosition);
return result;
}
複製代碼
目前GroupItemDecoration的1.0.0版本實現思路就所有講完了,後續更新還會解決GroupView內部控件各類事件的響應問題以及擴展更多的功能,若是你們看了感受還不錯麻煩點個贊,大家的支持是我最大的動力~
本次更新追加了新的接口,能夠監聽GroupItem的點擊與長按事件(暫不支持GroupItem的子控件)
recyclerView.addOnItemTouchListener(new GroupItemClickListener(groupItemDecoration,new GroupItemClickListener.OnGroupItemClickListener() {
@Override
public void onGroupItemClick(GroupItem groupItem) {
}
@Override
public void onGroupItemLongClick(GroupItem groupItem) {
}
}));
複製代碼
效果如圖