【Android】RecyclerView優(yōu)雅實(shí)現(xiàn)二級(jí)列表

ExpanableRecyclerView

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

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

自定義支持二級(jí)菜單的RecyclerViewAdapter蝇裤。

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

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

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

因?yàn)閛nCreateViewHolder和onBindViewHolder本來(lái)即是RecyclerViewAdapter需要強(qiáng)制Override的方法怠李,這里按父子關(guān)系拆分成了兩個(gè)方法针姿。而getGroupCount和getGroupItem在大概率情況下都是基于List的簡(jiǎn)單一行代碼即可實(shí)現(xiàn)乒省,故而使用起來(lái)十分簡(jiǎn)便。

Gradle

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

優(yōu)點(diǎn)

  1. 使用便捷钝满、簡(jiǎn)潔明了
  2. 最大程度保留RecyclerView的原生機(jī)制兜粘,滑動(dòng)到具體條目才進(jìn)行渲染,不會(huì)滑到另一個(gè)Group渲染另一個(gè)Group下所有子Item
  3. itemView的部分刷新弯蚜,可以自定義展開孔轴、閉合時(shí)的刷新機(jī)制,避免GroupItem在展開閉合時(shí)刷新整個(gè)GroupItem(比如只是簡(jiǎn)單的箭頭指向改變)
  4. 采用泛型熟吏,用戶自定義傳入?yún)?shù)距糖,擴(kuò)展性更高

使用方法

定義父子數(shù)據(jù)結(jié)構(gòu)

其中GroupBean需要繼承自BaseGroupBean并override三個(gè)方法玄窝。

  • getChildCount
    • 獲取子節(jié)點(diǎn)個(gè)數(shù)
  • isExpandable
    • 是否為可展開的節(jié)點(diǎn)
    • 默認(rèn)實(shí)現(xiàn)可以是判斷子節(jié)點(diǎn)是否為0,但是也可以做其他處理
  • getChildAt
    • 根據(jù)index獲取對(duì)應(yīng)的子節(jié)點(diǎn)數(shù)據(jù)結(jié)構(gòu)
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 {
}

定義對(duì)應(yīng)的ViewHolder

其中Group對(duì)應(yīng)的ViewHolder要繼承BaseGroupViewHolder并改寫onExpandStatusChanged.

該方法是實(shí)現(xiàn)item局部刷新的方法悍引,在展開恩脂、閉合時(shí)會(huì)回調(diào),比如對(duì)于大多數(shù)情況趣斤,開關(guān)閉合狀態(tài)只需要修改左邊箭頭指向俩块,就無(wú)需刷新itemView的其他部分。

實(shí)現(xiàn)原理是使用RecyclerView的payload機(jī)制實(shí)現(xiàn)局部監(jiān)聽刷新浓领。

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.只更新左側(cè)展開玉凯、閉合箭頭
      foldIv.setImageResource(isExpanding ? R.drawable.ic_arrow_expanding : R.drawable.ic_arrow_folding);
      
      // 2.默認(rèn)刷新整個(gè)Item
      relatedAdapter.notifyItemChanged(getAdapterPosition());
    }
}

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

使用自定義Adapter繼承基類

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

    @Override
    public int getGroupCount() {
        // 父節(jié)點(diǎn)個(gè)數(shù)
    }

    @Override
    public GroupBean getGroupItem(int groupIndex) {
        // 獲取父節(jié)點(diǎn)
    }

    @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) {
    }
}

其他用法

增加父子的種類

通過(guò)改寫getChildType和getGroupType方法進(jìn)行控制type联贩,該type會(huì)在onCreateGroupViewHolder和onCreateChildViewHolder時(shí)回傳漫仆。

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);

增加列表為空時(shí)候的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);

監(jiān)聽事件

可以通過(guò)setListener的方式設(shè)置監(jiān)聽事件。

public interface ExpandableRecyclerViewOnClickListener<GroupBean extends BaseGroupBean, ChildBean> {

        /**
         * 長(zhǎng)按時(shí)的操作
         *
         * @param groupItem
         * @return
         */
        boolean onGroupLongClicked(GroupBean groupItem);

        /**
         * 在可展開group被點(diǎn)擊的時(shí)候觸發(fā)的回調(diào)泪幌,返回布爾值表示是否攔截該操作
         *
         * @param groupItem
         * @param isExpand
         * @return true 使點(diǎn)擊無(wú)效盲厌。false 正常執(zhí)行展開、閉合操作祸泪。
         */
        boolean onInterceptGroupExpandEvent(GroupBean groupItem, boolean isExpand);

        /**
         * 點(diǎn)擊GroupView時(shí)的操作(該Group的isExpandable返回false才會(huì)觸發(fā)這個(gè)回調(diào))
         *
         * @param groupItem
         */
        void onGroupClicked(GroupBean groupItem);

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

實(shí)現(xiàn)原理

父子結(jié)構(gòu)劃分

  1. 通過(guò)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;

// 通過(guò)getItemView判斷類型没隘,這里默認(rèn)是使用上面定義的MASK懂扼,可以重載使Group和Child中再劃分子類,但是不允許和TYPE_MASK沖突右蒲,否則會(huì)報(bào)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中進(jìn)行類型判斷阀湿,調(diào)用不同的方法,這些方法在子類中進(jìn)行重載瑰妄。注意這里將這三個(gè)方法都置為final炕倘,防止子類重載,子類只能重載對(duì)應(yīng)不同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()));
    }
}

展開閉合操作

操作

當(dāng)groupBean的isExpandable返回true的時(shí)候,為itemView設(shè)置點(diǎn)擊事件啊央,進(jìn)行展開閉合眶诈。

展開閉合的具體原理是在Set中記錄展開閉合情況,當(dāng)發(fā)生展開瓜饥、閉合操作的時(shí)候進(jìn)行更新逝撬,并使用notifyItemChange接口進(jìn)行列表的局部刷新。

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());
                    }
                }
            }
        });
    }
    // 子類實(shí)現(xiàn)
    onBindGroupViewHolder(holder, groupBean, isGroupExpand(groupBean));
}

局部刷新原理

定義了Payload乓土,采用Payload機(jī)制進(jìn)行局部刷新宪潮。

在notifyItemChange時(shí)傳入payload溯警,在onBindViewHolder操作中判斷是否帶有payload,若帶有payload狡相,則執(zhí)行部分刷新的操作梯轻。

private static final Object EXPAND_PAYLOAD = new Object();

// 局部刷新時(shí)調(diào)用的接口(已封裝好,用戶無(wú)需調(diào)用)
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方法有抽象方法尽棕,在此方法中實(shí)現(xiàn)具體的展開喳挑、閉合邏輯
            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/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市滔悉,隨后出現(xiàn)的幾起案子伊诵,更是在濱河造成了極大的恐慌,老刑警劉巖回官,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件曹宴,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡歉提,警方通過(guò)查閱死者的電腦和手機(jī)笛坦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)唯袄,“玉大人弯屈,你說(shuō)我怎么就攤上這事×悼剑” “怎么了资厉?”我有些...
    開封第一講書人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蔬顾。 經(jīng)常有香客問(wèn)我宴偿,道長(zhǎng),這世上最難降的妖魔是什么诀豁? 我笑而不...
    開封第一講書人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任窄刘,我火速辦了婚禮,結(jié)果婚禮上舷胜,老公的妹妹穿的比我還像新娘娩践。我一直安慰自己,他們只是感情好烹骨,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開白布翻伺。 她就那樣靜靜地躺著,像睡著了一般沮焕。 火紅的嫁衣襯著肌膚如雪吨岭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,736評(píng)論 1 312
  • 那天峦树,我揣著相機(jī)與錄音辣辫,去河邊找鬼旦事。 笑死,一個(gè)胖子當(dāng)著我的面吹牛急灭,可吹牛的內(nèi)容都是我干的姐浮。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼化戳,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼单料!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起点楼,我...
    開封第一講書人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤扫尖,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后掠廓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體换怖,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年蟀瞧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了沉颂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡悦污,死狀恐怖铸屉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情切端,我是刑警寧澤彻坛,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站踏枣,受9級(jí)特大地震影響昌屉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜茵瀑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一间驮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧马昨,春花似錦竞帽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至笛谦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間昌阿,已是汗流浹背饥脑。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工恳邀, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人灶轰。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓谣沸,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親笋颤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子乳附,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容