1 Star 0 Fork 0

Elliott / SwipeRecyclerView

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

我的主页:http://www.yanzhenjie.com
欢迎关注我的微博:http://weibo.com/yanzhenjieit

QQ技术交流群:547839514


本库是基于RecyclerView的封装。

注意:本库在1.1.0版做了全新升级,没有最1.0.x版本做向下兼容,但是新版在API使用和功能方面都是个全新的升级。使用旧版本的同学升级时需要把ReadMe和Demo认真看一遍。

特性

  1. 基于List/Grid/StaggeredGridLayoutManagerItem侧滑菜单。
  2. Item两侧侧滑菜单支持水平分布、垂直分布。
  3. Item拖拽排序、侧滑删除。
  4. 随时添加或者移除HeaderViewFooterView
  5. 提供自动/点击加载更多的功能。[为什么没有下拉刷新?][ListView和GridView怎么办?]
  6. SwipeMenuLayout在任何地方都可以实现你自己的侧滑菜单。
  7. ViewPagerDrawerLayout等滑动布局嵌套使用。
  8. Sticky普通布局黏贴和ReyclerView分组黏贴。

注意:使用本库只需要使用SwipeMenuRecyclerView即可,可是使用任何第三方的Adapter,比如BaseRecyclerViewAdapterHelper

截图

对上面提到的效果都例举演示,但不是全部,更多效果可以下载Demo查看。

Item侧滑菜单

Item侧滑删除、拖拽

下拉刷新和加载更多

HeaderView和FooterView

Sticky效果和Item分组

和DrawerLayout嵌套

如何使用

首先引入SwipeRecyclerView到你的项目中,然后就可以进行开发工作了。

引入

  • Gradle
compile 'com.yanzhenjie:recyclerview-swipe:1.1.3'
  • Maven
<dependency>
  <groupId>com.yanzhenjie</groupId>
  <artifactId>recyclerview-swipe</artifactId>
  <version>1.1.3</version>
  <type>pom</type>
</dependency>

开发

在xml中引用SwipeRecyclerView:

<com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView
    .../>

注意

  1. 新版从1.1.0开始不再需要继承SwipeMenuAdapter了,只需要使用SwipeMenuRecyclerView即可。
  2. 如果添加了HeaderView,凡是通过ViewHolder拿到的position都要减掉HeaderView的数量才能得到正确的item position

ItemDecoration

也就是分割线,支持Grid形式和Linear形式,可以选择某个ViewType不画分割线:

// 默认构造,传入颜色即可。
new DefaultDecoration(color);

// 颜色,宽,高,最后一个参数是不画分割线的ViewType,可以传入多个。
new DefaultDecoration(color, width, height, excludeViewType);

// 例如下面的123都是不画分割线的ViewType:
new DefaultDecoration(color, width, height, 1, 2, 3);

Item点击监听

recyclerView.setSwipeItemClickListener(new SwipeItemClickListener() {
    @Override
    public void onItemClick(View view, int position) {
        // TODO,搞事情...
    }
});

侧滑菜单

// 设置监听器。
swipeRecyclerView.setSwipeMenuCreator(mSwipeMenuCreator);

// 创建菜单:
SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
    @Override
    public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
        SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
            ...; // 各种文字和图标属性设置。
        leftMenu.addMenuItem(deleteItem); // 在Item左侧添加一个菜单。

        SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
            ...; // 各种文字和图标属性设置。
        leftMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
        
        // 注意:哪边不想要菜单,那么不要添加即可。
    }
};

// 菜单点击监听。
swipeRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);

SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
    @Override
    public void onItemClick(SwipeMenuBridge menuBridge) {
        // 任何操作必须先关闭菜单,否则可能出现Item菜单打开状态错乱。
        menuBridge.closeMenu();
        
        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
    }
};

注意:菜单需要设置高度,关于菜单高度:

  1. MATCH_PARENT,自动适应Item高度,保持和Item一样高,比较推荐;
  2. 指定具体的高,比如80;
  3. WRAP_CONTENT,自身高度,极不推荐;

侧滑删除和拖拽

拖拽和侧滑删除的功能默认关闭的,所以先要打开功能:

recyclerView.setLongPressDragEnabled(true); // 拖拽排序,默认关闭。
recyclerView.setItemViewSwipeEnabled(true); // 策划删除,默认关闭。

只需要设置上面两个属性就可以进行相应的动作了,如果不需要哪个,不要打开就可以了。

然后监听拖拽和侧滑的动作,进行数据更新:

recyclerView.setOnItemMoveListener(mItemMoveListener);// 监听拖拽,更新UI。

OnItemMoveListener mItemMoveListener = new OnItemMoveListener() {
    @Override
    public boolean onItemMove(ViewHolder srcHolder, ViewHolder targetHolder) {
        int fromPosition = srcHolder.getAdapterPosition();
        int toPosition = targetHolder.getAdapterPosition();
        
        // Item被拖拽时,交换数据,并更新adapter。
        Collections.swap(mDataList, fromPosition, toPosition);
        adapter.notifyItemMoved(fromPosition, toPosition);
        return true;
    }

    @Override
    public void onItemDismiss(ViewHolder srcHolder) {
        int position = srcHolder.getAdapterPosition();
        // Item被侧滑删除时,删除数据,并更新adapter。
        mDataList.remove(position);
        adapter.notifyItemRemoved(position);
    }
};

特别注意:如果LayoutManagerList形式,那么Item拖拽时只能从1-2-3-4这样走,如果你的LayoutManagerGrid形式的,那么Item可以从1直接到3或者5或者6...,这样数据就会错乱,所以LayoutManager是Grid形式时这里要特别注意转换数据位置的算法:

@Override
public boolean onItemMove(ViewHolder srcHolder, ViewHolder targetHolder) {
    int fromPosition = srcHolder.getAdapterPosition();
    int toPosition = targetHolder.getAdapterPosition();
    if (fromPosition < toPosition)
        for (int i = fromPosition; i < toPosition; i++)
            Collections.swap(mDataList, i, i + 1);
    else
        for (int i = fromPosition; i > toPosition; i--)
            Collections.swap(mDataList, i, i - 1);

    mMenuAdapter.notifyItemMoved(fromPosition, toPosition);
    return true;
}

我们还可以监听用户的侧滑删除和拖拽Item时的手指状态:

recyclerView.setOnItemStateChangedListener(mStateChangedListener);

...

private OnItemStateChangedListener mStateChangedListener = (viewHolder, actionState) -> {
    if (actionState == OnItemStateChangedListener.ACTION_STATE_DRAG) {
        // 状态:正在拖拽。
    } else if (actionState == OnItemStateChangedListener.ACTION_STATE_SWIPE) {
        // 状态:滑动删除。
    } else if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {
        // 状态:手指松开。
    }
};

想用户触摸到某个Item时就开始拖拽或者侧滑删除时,只需要调用startDrag()startSwipe()并转入当前ItemViewHoler即可。

触摸拖拽:

swipeRecyclerView.startDrag(ViewHolder);

触摸侧滑删除:

swipeRecyclerView.startSwipe(ViewHolder);

HeaderView和FooterView

主要方法:

addHeaderView(View); // 添加HeaderView。
removeHeaderView(View); // 移除HeaderView。
addFooterView(View); // 添加FooterView。
removeFooterView(View); // 移除FooterView。
getHeaderItemCount(); // 获取HeaderView个数。
getFooterItemCount(); // 获取FooterView个数。
getItemViewType(int); // 获取Item的ViewType,包括HeaderView、FooterView、普通ItemView。

添加/移除HeaderView/FooterView喝setAdapter()的调用不分先后顺序。

特别注意

  1. 如果添加了HeaderView,凡是通过ViewHolder拿到的position都要减掉HeaderView的数量才能得到正确的item position

加载更多

本库默认提供了加载更多的动画和View,开发者也可以自定义;默认支持RecyclerView自带的三种布局管理器。

默认加载更多:

RecyclerView recyclerView = ...
...

recyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
recyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。

LoadMoreListener mLoadMoreListener = new LoadMoreListener() {
    @Override
    public void onLoadMore() {
        // 该加载更多啦。
        
        ... // 请求数据,并更新数据源操作。
        mMainAdapter.notifyDataSetChanged();

        // 数据完更多数据,一定要调用这个方法。
        // 第一个参数:表示此次数据是否为空。
        // 第二个参数:表示是否还有更多数据。
        mRecyclerView.loadMoreFinish(false, true);

        // 如果加载失败调用下面的方法,传入errorCode和errorMessage。
        // errorCode随便传,你自定义LoadMoreView时可以根据errorCode判断错误类型。
        // errorMessage是会显示到loadMoreView上的,用户可以看到。
        // mRecyclerView.loadMoreError(0, "请求网络失败");
    }
};

自定义加载更多View也很简单,自定义一个View,并实现一个接口即可:

public class DefineLoadMoreView extends LinearLayout
        implements SwipeMenuRecyclerView.LoadMoreView,
        View.OnClickListener {

    private LoadMoreListener mLoadMoreListener;

    public DefineLoadMoreView(Context context) {
        super(context);
        ...
        setOnClickListener(this);
    }

    /**
     * 马上开始回调加载更多了,这里应该显示进度条。
     */
    @Override
    public void onLoading() {
        // 展示加载更多的动画和提示信息。
        ...
    }

    /**
     * 加载更多完成了。
     *
     * @param dataEmpty 是否请求到空数据。
     * @param hasMore   是否还有更多数据等待请求。
     */
    @Override
    public void onLoadFinish(boolean dataEmpty, boolean hasMore) {
        // 根据参数,显示没有数据的提示、没有更多数据的提示。
        // 如果都不存在,则都不用显示。
    }

    /**
     * 加载出错啦,下面的错误码和错误信息二选一。
     *
     * @param errorCode    错误码。
     * @param errorMessage 错误信息。
     */
    @Override
    public void onLoadError(int errorCode, String errorMessage) {
    }

    /**
     * 调用了setAutoLoadMore(false)后,在需要加载更多的时候,此方法被调用,并传入listener。
     */
    @Override
    public void onWaitToLoadMore(SwipeMenuRecyclerView.LoadMoreListener loadMoreListener) {
        this.mLoadMoreListener = loadMoreListener;
        }

    /**
     * 非自动加载更多时mLoadMoreListener才不为空。
     */
    @Override
    public void onClick(View v) {
        if (mLoadMoreListener != null) mLoadMoreListener.onLoadMore();
    }
}

混淆

-keepclasseswithmembers class android.support.v7.widget.RecyclerView$ViewHolder {
   public final View *;
}

其它类都是可以混淆的,如果添加了上述规则后还是存在问题,那么再追加:

-dontwarn com.yanzhenjie.recyclerview.swipe.**
-keep class com.yanzhenjie.recyclerview.swipe.** {*;}

引用资料

加载更多的灵感来自cube-sdk,侧滑菜单参考了SwipeMenu,添加HeaderView参考了HeaderAndFooterWrapper类,特别感谢上述开源库及其作者。

License

Copyright 2017 Yan Zhenjie

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 Yan Zhenjie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

暂无描述 展开 收起
Android
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Android
1
https://gitee.com/ylzheng/SwipeRecyclerView.git
git@gitee.com:ylzheng/SwipeRecyclerView.git
ylzheng
SwipeRecyclerView
SwipeRecyclerView
master

搜索帮助