【Android】RecyclerView優雅實現二級列表

ExpanableRecyclerView

[圖片上傳失敗...(image-8fdb49-1510531851002)]

github:https://github.com/hgDendi/ExpandableRecyclerView

自定義支持二級菜單的RecyclerViewAdapter。

將展開閉合操作封裝在了BaseExpandableRecyclerViewAdapter中,使整個使用方式充滿彈性。

下方有具體使用方法,一般需要override 6個方法:

  • getGroupCount
  • getGroupItem
  • onCreateGroupViewHolder
  • onCreateChildViewHolder
  • onBindGroupViewHolder
  • onBindChildViewHolder

因為onCreateViewHolder和onBindViewHolder本來即是RecyclerViewAdapter需要強制Override的方法,這里按父子關系拆分成了兩個方法。而getGroupCount和getGroupItem在大概率情況下都是基于List的簡單一行代碼即可實現,故而使用起來十分簡便。

Gradle

dependencies{
    compile 'com.hgDendi:expandable-recyclerview-adapter:1.0.1'
}

優點

  1. 使用便捷、簡潔明了
  2. 最大程度保留RecyclerView的原生機制,滑動到具體條目才進行渲染,不會滑到另一個Group渲染另一個Group下所有子Item
  3. itemView的部分刷新,可以自定義展開、閉合時的刷新機制,避免GroupItem在展開閉合時刷新整個GroupItem(比如只是簡單的箭頭指向改變)
  4. 采用泛型,用戶自定義傳入參數,擴展性更高

使用方法

定義父子數據結構

其中GroupBean需要繼承自BaseGroupBean并override三個方法。

  • getChildCount
    • 獲取子節點個數
  • isExpandable
    • 是否為可展開的節點
    • 默認實現可以是判斷子節點是否為0,但是也可以做其他處理
  • getChildAt
    • 根據index獲取對應的子節點數據結構
class SampleGroupBean implements BaseExpandableRecyclerViewAdapter.BaseGroupBean<SampleChildBean> {
    @Override
    public int getChildCount() {
        return mList.size();
    }

    // whether this group is expandable
    @Override
    public boolean isExpandable() {
        return getChildCount() > 0;
    }
  
    @Override
    public SampleChildBean getChildAt(int index) {
        return mList.size() <= index ? null : mList.get(index);
    }
}

public class SampleChildBean {
}

定義對應的ViewHolder

其中Group對應的ViewHolder要繼承BaseGroupViewHolder并改寫onExpandStatusChanged.

該方法是實現item局部刷新的方法,在展開、閉合時會回調,比如對于大多數情況,開關閉合狀態只需要修改左邊箭頭指向,就無需刷新itemView的其他部分。

實現原理是使用RecyclerView的payload機制實現局部監聽刷新。

static class GroupVH extends BaseExpandableRecyclerViewAdapter.BaseGroupViewHolder {
    GroupVH(View itemView) {
        super(itemView);
    }

    // this method is used for partial update.Which means when expand status changed,only a part of this view need to invalidate
    @Override
    protected void onExpandStatusChanged(RecyclerView.Adapter relatedAdapter, boolean isExpanding) {
      // 1.只更新左側展開、閉合箭頭
      foldIv.setImageResource(isExpanding ? R.drawable.ic_arrow_expanding : R.drawable.ic_arrow_folding);
      
      // 2.默認刷新整個Item
      relatedAdapter.notifyItemChanged(getAdapterPosition());
    }
}

static class ChildVH extends RecyclerView.ViewHolder {
    ChildVH(View itemView) {
        super(itemView);
    }
}

使用自定義Adapter繼承基類

// !!注意這里繼承時候使用的泛型,分別為上面提到的Bean和ViewHolder
public class SampleAdapter extends BaseExpandableRecyclerViewAdapter
<SampleGroupBean, SampleChildBean, SampleAdapter.GroupVH, SampleAdapter.ChildVH>

    @Override
    public int getGroupCount() {
        // 父節點個數
    }

    @Override
    public GroupBean getGroupItem(int groupIndex) {
        // 獲取父節點
    }

    @Override
    public GroupVH onCreateGroupViewHolder(ViewGroup parent, int groupViewType) {
    }

    @Override
    public ChildVH onCreateChildViewHolder(ViewGroup parent, int childViewType) {
    }

    @Override
    public void onBindGroupViewHolder(GroupVH holder, SampleGroupBean sampleGroupBean, boolean isExpand) {
    }

    @Override
    public void onBindChildViewHolder(ChildVH holder, SampleGroupBean sampleGroupBean, SampleChildBean sampleChildBean) {
    }
}

其他用法

增加父子的種類

通過改寫getChildType和getGroupType方法進行控制type,該type會在onCreateGroupViewHolder和onCreateChildViewHolder時回傳。

protected int getGroupType(GroupBean groupBean) {
    return 0;
}

abstract public GroupViewHolder onCreateGroupViewHolder(ViewGroup parent, int groupViewType);
    
protected int getChildType(GroupBean groupBean, ChildBean childBean) {
    return 0;
}

abstract public ChildViewHolder onCreateChildViewHolder(ViewGroup parent, int childViewType);

增加列表為空時候的EmptyView

adapter.setEmptyViewProducer(new ViewProducer() {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        View emptyView = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty, parent, false);
        return new DefaultEmptyViewHolder(emptyView);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder) {
    }
});

增加HeaderView

adapter.setEmptyViewProducer(new ViewProducer() {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        View emptyView = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
        return new DefaultEmptyViewHolder(emptyView);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder) {
    }
},false);

監聽事件

可以通過setListener的方式設置監聽事件。

public interface ExpandableRecyclerViewOnClickListener<GroupBean extends BaseGroupBean, ChildBean> {

        /**
         * 長按時的操作
         *
         * @param groupItem
         * @return
         */
        boolean onGroupLongClicked(GroupBean groupItem);

        /**
         * 在可展開group被點擊的時候觸發的回調,返回布爾值表示是否攔截該操作
         *
         * @param groupItem
         * @param isExpand
         * @return true 使點擊無效。false 正常執行展開、閉合操作。
         */
        boolean onInterceptGroupExpandEvent(GroupBean groupItem, boolean isExpand);

        /**
         * 點擊GroupView時的操作(該Group的isExpandable返回false才會觸發這個回調)
         *
         * @param groupItem
         */
        void onGroupClicked(GroupBean groupItem);

        /**
         * 點擊子View時的操作
         *
         * @param groupItem
         * @param childItem
         */
        void onChildClicked(GroupBean groupItem, ChildBean childItem);
    }

實現原理

父子結構劃分

  1. 通過getItemType判斷所處類型,在基類中就先劃分為四種類型的View。
private static final int TYPE_EMPTY = ViewProducer.VIEW_TYPE_EMPTY;
private static final int TYPE_HEADER = ViewProducer.VIEW_TYPE_HEADER;
private static final int TYPE_GROUP = ViewProducer.VIEW_TYPE_EMPTY >> 2;
private static final int TYPE_CHILD = ViewProducer.VIEW_TYPE_EMPTY >> 3;
private static final int TYPE_MASK = TYPE_GROUP | TYPE_CHILD | TYPE_EMPTY | TYPE_HEADER;

// 通過getItemView判斷類型,這里默認是使用上面定義的MASK,可以重載使Group和Child中再劃分子類,但是不允許和TYPE_MASK沖突,否則會報Exception
@Override
public final int getItemViewType(int position) {
    if (mIsEmpty) {
        return position == 0 && mShowHeaderViewWhenEmpty ? TYPE_HEADER : TYPE_EMPTY;
    }
    if (position == 0 && mHeaderViewProducer != null) {
        return TYPE_HEADER;
    }
    int[] coord = translateToDoubleIndex(position);
    GroupBean groupBean = getGroupItem(coord[0]);
    if (coord[1] < 0) {
        int groupType = getGroupType(groupBean);
        if ((groupType & TYPE_MASK) == 0) {
            return groupType | TYPE_GROUP;
        } else {
            throw new IllegalStateException(
                String.format(Locale.getDefault(), "GroupType [%d] conflits with MASK [%d]", groupType, TYPE_MASK));
        }
    } else {
        int childType = getChildType(groupBean, groupBean.getChildAt(coord[1]));
        if ((childType & TYPE_MASK) == 0) {
            return childType | TYPE_CHILD;
        } else {
            throw new IllegalStateException(
                String.format(Locale.getDefault(), "ChildType [%d] conflits with MASK [%d]", childType, TYPE_MASK));
        }
    }
}
  1. 在onCreateViewHolder和onBindViewHolder中進行類型判斷,調用不同的方法,這些方法在子類中進行重載。注意這里將這三個方法都置為final,防止子類重載,子類只能重載對應不同type的具體方法。
@Override
public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType & TYPE_MASK) {
        case TYPE_EMPTY:
            return mEmptyViewProducer.onCreateViewHolder(parent);
        case TYPE_HEADER:
            return mHeaderViewProducer.onCreateViewHolder(parent);
        case TYPE_CHILD:
            return onCreateChildViewHolder(parent, viewType ^ TYPE_CHILD);
        case TYPE_GROUP:
            return onCreateGroupViewHolder(parent, viewType ^ TYPE_GROUP);
        default:
            throw new IllegalStateException(
                String.format(Locale.getDefault(), "Illegal view type : viewType[%d]", viewType));
    }
}

@Override
public final void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
    onBindViewHolder(holder, position, null);
}

@Override
public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List<Object> payloads) {
    switch (holder.getItemViewType() & TYPE_MASK) {
        case TYPE_EMPTY:
            mEmptyViewProducer.onBindViewHolder(holder);
            break;
        case TYPE_HEADER:
            mHeaderViewProducer.onBindViewHolder(holder);
            break;
        case TYPE_CHILD:
            final int[] childCoord = translateToDoubleIndex(position);
            GroupBean groupBean = getGroupItem(childCoord[0]);
            bindChildViewHolder((ChildViewHolder) holder, groupBean, groupBean.getChildAt(childCoord[1]), payloads);
            break;
        case TYPE_GROUP:
            bindGroupViewHolder((GroupViewHolder) holder,
                getGroupItem(translateToDoubleIndex(position)[0]), payloads);
            break;
        default:
            throw new IllegalStateException(
                String.format(Locale.getDefault(), "Illegal view type : position [%d] ,itemViewType[%d]", position, holder.getItemViewType()));
    }
}

展開閉合操作

操作

當groupBean的isExpandable返回true的時候,為itemView設置點擊事件,進行展開閉合。

展開閉合的具體原理是在Set中記錄展開閉合情況,當發生展開、閉合操作的時候進行更新,并使用notifyItemChange接口進行列表的局部刷新。

private Set<GroupBean> mExpandGroupSet;

protected void bindGroupViewHolder(final GroupViewHolder holder, final GroupBean groupBean, List<Object> payload) {
    // ...
    if (!groupBean.isExpandable()) {
      // ...
    } else {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final boolean isExpand = mExpandGroupSet.contains(groupBean);
                if (mListener == null || !mListener.onInterceptGroupExpandEvent(groupBean, isExpand)) {
                final int adapterPosition = holder.getAdapterPosition();
                holder.onExpandStatusChanged(BaseExpandableRecyclerViewAdapter.this, !isExpand);
                    if (isExpand) {
                        mExpandGroupSet.remove(groupBean);
                        notifyItemRangeRemoved(adapterPosition + 1, groupBean.getChildCount());
                    } else {
                        mExpandGroupSet.add(groupBean);
                        notifyItemRangeInserted(adapterPosition + 1, groupBean.getChildCount());
                    }
                }
            }
        });
    }
    // 子類實現
    onBindGroupViewHolder(holder, groupBean, isGroupExpand(groupBean));
}

局部刷新原理

定義了Payload,采用Payload機制進行局部刷新。

在notifyItemChange時傳入payload,在onBindViewHolder操作中判斷是否帶有payload,若帶有payload,則執行部分刷新的操作。

private static final Object EXPAND_PAYLOAD = new Object();

// 局部刷新時調用的接口(已封裝好,用戶無需調用)
notifyItemChanged(position, EXPAND_PAYLOAD);

// 處理payload
protected void bindGroupViewHolder(final GroupViewHolder holder, final GroupBean groupBean, List<Object> payload) {
    if (payload != null && payload.size() != 0) {
        if (payload.contains(EXPAND_PAYLOAD)) {
            // holder方法有抽象方法,在此方法中實現具體的展開、閉合邏輯
            holder.onExpandStatusChanged(BaseExpandableRecyclerViewAdapter.this, isGroupExpand(groupBean));
            if (payload.size() == 1) {
                return;
            }
        }
    onBindGroupViewHolder(holder, groupBean, isGroupExpand(groupBean), payload);
    return;
    }
}

License

MIT

https://rem.mit-license.org/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容