Android列表蜒车,篩選 讳嘱,使用RecyclerView的全選幔嗦、全不選、刪除

原文鏈接:http://www.reibang.com/p/7e1e0da67864

1.布局界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <include layout="@layout/action_common_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <RelativeLayout
        android:id="@+id/layout_edit"
        android:layout_width="match_parent"
        android:layout_height="@dimen/head_line_height"
        android:visibility="gone"
        tools:visibility="visible">

        <RadioButton
            android:id="@+id/rb_select_all"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="全選"
            android:textColor="@color/shop_text_selecter"
            android:textSize="16sp" />

        <Button
            android:id="@+id/btn_del"
            style="@style/DefaultOrangeButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="4dp"
            android:layout_marginRight="16dp"
            android:layout_marginBottom="4dp"
            android:text="刪除" />
    </RelativeLayout>
</LinearLayout>
2.RecyclerView的適配器
public class MyCollectionAdapter extends BaseQuickAdapter<GoodsInfo, DataBindBaseViewHolder> {
    private ArrayList<Integer> selectArrays = new ArrayList<>();//選中數(shù)據(jù)項在列表中的位置集合
    private boolean isShowSelectBtn;//是否顯示選中按鈕,默認不顯示
    private boolean isSelectAll;//外部【全選】按鈕是否為選中狀態(tài)
    public onSelectAllListener listener;//選中和取消選中監(jiān)聽器

    public void setListener(onSelectAllListener listener) {
        this.listener = listener;
    }

    public interface onSelectAllListener {
        void cancleSelectAll();

        void selectAll();
    }

    public MyCollectionAdapter() {
        super(R.layout.item_my_collection);
    }

    /**
     * 選中/取消
     *
     * @param selectPosition
     */
    public void setSelectPosition(Integer selectPosition) {
        boolean contains = selectArrays.contains(selectPosition);
        if (contains) {
            selectArrays.remove(selectPosition);
            //取消一項后沥潭,如果全選按鈕的狀態(tài)為:選中邀泉,應(yīng)該取消全選按鈕選中狀態(tài),但不觸發(fā)取消所有列表已經(jīng)選中項的事件
            if (isSelectAll) {
                isSelectAll = false;
                if (listener != null) listener.cancleSelectAll();
            }
        } else {
            //如果添加一項后,(外部[全選按鈕]為:未選中&&列表數(shù)據(jù)全部選中)钝鸽,那么設(shè)置全選按鈕為選中狀態(tài)汇恤,不觸發(fā)選中事件
            selectArrays.add(selectPosition);
            if (!isSelectAll && isSelectAllData()) {
                isSelectAll = true;
                if (listener != null) listener.selectAll();
            }
        }
        Collections.sort(selectArrays);
        notifyItemChanged(selectPosition);
    }

    /**
     * 全選
     */
    public void selectAll() {
        for (int i = 0; i < mData.size(); i++) {
            boolean contains = selectArrays.contains(i);
            if (!contains) selectArrays.add(i);
        }
        Collections.sort(selectArrays);//進行排序,避免因為選擇前后順序不一致拔恰,導(dǎo)致更新位置越界
        L.e("selectArrays==" + selectArrays.toString());
        notifyDataSetChanged();
        isSelectAll = true;
    }

    /**
     * 取消全選
     */
    public void cancleAll() {
        selectArrays.clear();
        notifyDataSetChanged();
        isSelectAll = false;
    }

    /**
     * 是否選中了所有的數(shù)據(jù)
     * 用來設(shè)定RadioButton狀態(tài)
     */
    public boolean isSelectAllData() {
        return mData.size() == selectArrays.size();
    }

    /**
     * 刪除選中項
     * position 為選中數(shù)據(jù)項在列表中的位置因谎,如0,1,2,3
     * i 為當前集合遍歷位置颜懊,所以remove()移除時要使用position-i
     * 例如選中 position  1和3财岔,那么遍歷兩次i為 0,1
     * 由于第一次移除位置1的時候,列表數(shù)據(jù)少了一項河爹,所以原來位置為3的變成了位置2匠璧,所以3-1=2
     * 也就是position-i才會拿到正確的列表數(shù)據(jù)位置
     */
    public void delSelect() {
        for (int i = 0; i < selectArrays.size(); i++) {
            Integer position = selectArrays.get(i);
            remove(position - i);
        }
        selectArrays.clear();
    }

    /**
     * 獲得所有選中的收藏,并組裝為id集合,以“咸这,”分割的字符串
     * 方便接口刪除收藏項
     *
     * @return
     */
    public String getAllSelectIds() {
        if (selectArrays.size() == 0) return "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < selectArrays.size(); i++) {
            GoodsInfo dataBean = mData.get(selectArrays.get(i));
            String goodsId = dataBean.getItemId();
            buffer.append(goodsId);
            if (i < selectArrays.size() - 1) buffer.append(",");
        }
        return buffer.toString();
    }

    /**
     * 顯示和隱藏操作按鈕
     *
     * @param showSelectBtn
     */
    public void setShowSelectBtn(boolean showSelectBtn) {
        isShowSelectBtn = showSelectBtn;
        notifyDataSetChanged();
    }

    @Override
    protected void convert(DataBindBaseViewHolder helper, GoodsInfo item) {
        ItemMyCollectionBinding binding = (ItemMyCollectionBinding) helper.getBinding();
        binding.setItem(item);
        binding.couponPrice.setCouponText(item.getCouponMoney() + "元");
        helper.addOnClickListener(R.id.rb_select);
        //是否顯示操作按鈕
        if (isShowSelectBtn) {
            binding.rbSelect.setVisibility(View.VISIBLE);
            boolean contains = selectArrays.contains(helper.getLayoutPosition());//是否選中
            binding.rbSelect.setChecked(contains);
        } else {
            binding.rbSelect.setVisibility(View.GONE);
        }
    }

}

其中適配器布局文件item_my_collection

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <import type="cn.com.smallcake_utils.SpannableStringUtils" />
        <variable
            name="item"
            type="**.GoodsInfo" />
    </data>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">
        <RadioButton
            android:id="@+id/rb_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:visibility="visible" />
        <ImageView
            android:id="@+id/iv_pict_url"
            imageRoundUrl="@{item.itemPic}"
            android:layout_width="130dp"
            android:layout_height="130dp"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@+id/rb_select"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"
            tools:src="@mipmap/logo" />
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="4dp"
            android:layout_marginRight="4dp"
            android:maxLines="2"
            android:text="@{item.itemTitle}"
            android:textColor="@color/text_black"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/iv_pict_url"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="嬰兒濕巾80抽x5包便攜式迷你帶蓋批發(fā)新生兒棉柔巾嬰兒濕巾80抽x5包便攜式迷你帶蓋批發(fā)新生兒棉柔巾" />
        <ImageView
            android:id="@+id/iv_user_type"
            isTmall="@{item.isTmall}"
            android:layout_width="14dp"
            android:layout_height="14dp"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            android:src="@mipmap/icon_tmall"
            app:layout_constraintStart_toEndOf="@+id/iv_pict_url"
            app:layout_constraintTop_toBottomOf="@+id/tv_title" />

        <TextView
            android:id="@+id/tv_shop_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="2dp"
            android:layout_marginLeft="2dp"
            android:layout_weight="1"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="@{item.shopName}"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="@+id/iv_user_type"
            app:layout_constraintEnd_toStartOf="@+id/tv_volume"
            app:layout_constraintStart_toEndOf="@+id/iv_user_type"
            app:layout_constraintTop_toTopOf="@+id/iv_user_type"
            tools:text="天真貝比旗艦店" />
        <TextView
            android:id="@+id/tv_volume"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:text='@{@string/sold+item.itemSale}'
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="@+id/tv_shop_title"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toEndOf="@+id/tv_shop_title"
            app:layout_constraintTop_toTopOf="@+id/tv_shop_title"
            app:layout_constraintVertical_bias="0.0"
            tools:text="@string/sold" />
        <TextView
            android:id="@+id/tv_commission_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/round2_pink_bg"
            android:ellipsize="start"
            android:paddingLeft="4dp"
            android:paddingTop="2dp"
            android:paddingRight="4dp"
            android:paddingBottom="2dp"
            android:singleLine="true"
            android:text='@{@string/ygsy_y+item.commision}'
            android:textColor="@color/tab_orange"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            tools:text="預(yù)估收益10元" />
        <**.CouponBg
            android:id="@+id/coupon_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toTopOf="@+id/tv_commission_price"
            app:layout_constraintEnd_toEndOf="parent"
            tools:coupon_price="15元" />
        <TextView
            android:id="@+id/tv_zk_final_price"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginBottom="8dp"
            android:ellipsize="start"
            android:singleLine="true"
            android:text='@{SpannableStringUtils.getBuilder(@string/quan_hou).setProportion(0.8f).append(@string/rmb_symbol).setProportion(0.7f).setBold().append(item.itemEndPrice).setBold().create()}'
            android:textColor="@color/tab_orange"
            android:textSize="16sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/tv_commission_price"
            app:layout_constraintStart_toEndOf="@+id/iv_pict_url"
            tools:text="券后¥19.8" />
        <TextView
            android:id="@+id/tv_reserve_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginBottom="4dp"
            android:text='@{SpannableStringUtils.getBuilder(@string/yuan_jia+item.itemPrice).setStrikethrough().create()}'
            android:textColor="@color/text_gray"
            android:textSize="11sp"
            app:layout_constraintBottom_toTopOf="@+id/tv_zk_final_price"
            app:layout_constraintStart_toEndOf="@+id/iv_pict_url"
            tools:text="原價¥149.9" />
        <View
            android:layout_width="match_parent"
            android:layout_height="1.5dp"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/h_gray_dot_line"
            android:layerType="software"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </android.support.constraint.ConstraintLayout>
</layout>
3.使用夷恍,主要就三個操作+適配器操作
    @OnClick({R.id.tv_right, R.id.rb_select_all, R.id.btn_del})
    public void doClicks(View view) {
        switch (view.getId()) {
            case R.id.tv_right://操作的顯示和隱藏
                edit();
                break;
            case R.id.rb_select_all://全選/取消全選
                clickSelectAll();
                break;
            case R.id.btn_del://刪除
                del();
                break;
        }
    }
  • a.點擊頂部右側(cè),來顯示和隱藏列表中的操作按鈕和底部的全選刪除按鈕edit()
    private void edit() {
        String s = tvRight.getText().toString();
        if (s.equals("管理")){
            tvRight.setText("取消");
            mAdapter.setShowSelectBtn(true);
            layoutEdit.setVisibility(View.VISIBLE);
        }else {
            tvRight.setText("管理");
            mAdapter.setShowSelectBtn(false);
            layoutEdit.setVisibility(View.GONE);
        }
    }
  • b.全選按鈕的觸發(fā)效果
    private void clickSelectAll() {
        if (mAdapter.isSelectAllData()) {
            rbSelectAll.setChecked(false);
            mAdapter.cancleAll();
        } else {
            rbSelectAll.setChecked(true);
            mAdapter.selectAll();
        }
    }
  • c.刪除
    private void del() {
        String allSelectIds = mAdapter.getAllSelectIds();
        if (TextUtils.isEmpty(allSelectIds)) {
            ToastUtil.showLong("未選中任何項媳维!");
            return;
        }
        //刷新適配器
        dataProvider.user.delCol(user.getUid(), user.getToken(), allSelectIds)
                .subscribe(new OnSuccessAndFailListener<BaseResponse>(dialog) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.showLong(baseResponse.getMsg());
                        //刷新適配器
                        mAdapter.delSelect();
                    }
                });
    }
  • d.適配器操作
    private void onEvent() {
        //加載更多
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (page < totalPages) {
                    page++;
                    getMyCollection();
                } else {
                    mAdapter.loadMoreEnd();
                }
            }
        }, recyclerView);
        //進入商品詳情
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsInfo item = (GoodsInfo) adapter.getItem(position);
                jumpToFragmentByType(item);
            }
        });

        //單條數(shù)據(jù)項的選中和取消選中
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mAdapter.setSelectPosition(position);
            }
        });

        //全選后酿雪,取消一項,解除全選按鈕選中狀態(tài),選中一項后侄刽,如果已經(jīng)全選指黎,改變?nèi)x按鈕狀態(tài)為選中
        mAdapter.setListener(new MyCollectionAdapter.onSelectAllListener() {
            @Override
            public void cancleSelectAll() {
                rbSelectAll.setChecked(false);
            }

            @Override
            public void selectAll() {
                rbSelectAll.setChecked(true);
            }
        });
    }

PS:適配器使用BaseRecyclerViewAdapterHelper+DataBind的方式,效果如下:

全選,單選
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末唠梨,一起剝皮案震驚了整個濱河市袋励,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖茬故,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盖灸,死亡現(xiàn)場離奇詭異,居然都是意外死亡磺芭,警方通過查閱死者的電腦和手機赁炎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钾腺,“玉大人徙垫,你說我怎么就攤上這事》虐簦” “怎么了姻报?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長间螟。 經(jīng)常有香客問我吴旋,道長,這世上最難降的妖魔是什么厢破? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任荣瑟,我火速辦了婚禮,結(jié)果婚禮上摩泪,老公的妹妹穿的比我還像新娘笆焰。我一直安慰自己,他們只是感情好见坑,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布嚷掠。 她就那樣靜靜地躺著,像睡著了一般鳄梅。 火紅的嫁衣襯著肌膚如雪叠国。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天戴尸,我揣著相機與錄音粟焊,去河邊找鬼。 笑死孙蒙,一個胖子當著我的面吹牛项棠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播挎峦,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼香追,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了坦胶?” 一聲冷哼從身側(cè)響起透典,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤晴楔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后峭咒,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體税弃,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年凑队,在試婚紗的時候發(fā)現(xiàn)自己被綠了则果。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡漩氨,死狀恐怖西壮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情叫惊,我是刑警寧澤款青,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站赋访,受9級特大地震影響可都,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蚓耽,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望旋炒。 院中可真熱鬧步悠,春花似錦、人聲如沸瘫镇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽铣除。三九已至谚咬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間尚粘,已是汗流浹背择卦。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留郎嫁,地道東北人秉继。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像泽铛,于是被迫代替她去往敵國和親尚辑。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355