RecyclerView 侧滑删除菜单 最简版 没有之一

网上有很多关于侧面滑动菜单的代码和文章,有的包含了很多功能,有的比较简单但是用起来有很多限制,修改起来比较坑多。
这里我写了一个最简版的侧面滑动功能,实现了主要的左滑菜单功能。

效果图
在这里插入图片描述

一、添加自定义属性:
在values 中创建 attrs.xml 文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyRecyclerViewItem">
        <attr name="left_width" format="integer"/>
        <attr name="right_width" format="integer"/>
        <attr name="move_range" format="integer"/>
    </declare-styleable>
</resources>

二、列表item 模板
im_test_item.xml

<?xml version="1.0" encoding="utf-8"?>
<com.chenxing.searchjob.sdk.view.MyRecyclerViewItem xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/scroll_item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none"
    app:move_range="20"
    app:right_width="200">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp">

        <LinearLayout
            android:id="@+id/content_layout"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:orientation="vertical">


            <!--内容区域放置布局-->

            <TextView
                android:id="@+id/show"
                android:layout_width="1000dp"
                android:layout_height="200dp"
                android:background="@color/colorPrimaryDark"
                android:gravity="center_vertical"
                android:text="点击试试"
                android:textColor="#ffffff"
                android:textSize="18sp"
                android:textStyle="bold" />

            <!--内容区域放置布局结束-->

        </LinearLayout>

        <LinearLayout
            android:id="@+id/rightLayout"
            android:layout_width="140dp"
            android:layout_height="match_parent"
            android:layout_alignTop="@id/content_layout"
            android:layout_alignBottom="@id/content_layout"
            android:layout_toEndOf="@id/content_layout"
            android:background="@color/colorAccent"
            android:gravity="center"
            android:orientation="horizontal"
            android:weightSum="2">

            <!--自定义侧边菜单布局-->

            <TextView
                android:id="@+id/click"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="删除"
                android:textColor="#ffffff"
                android:textSize="26sp" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@color/colorPrimary"
                android:gravity="center"
                android:text="修改"
                android:textColor="#ff839dff"
                android:textSize="26sp" />

            <!--自定义侧边菜单布局结束-->

        </LinearLayout>

    </RelativeLayout>


</com.chenxing.searchjob.sdk.view.MyRecyclerViewItem>

三、自定义控件核心代码:
MyRecyclerViewItem.java

package com.chenxing.searchjob.sdk.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;

import io.rong.imkit.R;

public class MyRecyclerViewItem extends HorizontalScrollView {


    public MyRecyclerViewItem(Context context) {
        super(context);
        init(context,null);
    }

    public MyRecyclerViewItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyRecyclerViewItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public static final String TAG=MyRecyclerViewItem.class.getSimpleName();
    private boolean isLeft = true;//默认左边
    private int rightLayoutWidth;
    private int leftLayoutWidth;
    private int range;

    public void setRightLayoutWidth(int rightLayoutWidth) {
        this.rightLayoutWidth = rightLayoutWidth;
    }

    public void setLeftLayoutWidth(int leftLayoutWidth) {
        this.leftLayoutWidth = leftLayoutWidth;
    }

    public void setRange(int range) {
        this.range = range;
    }

    private void init(Context context, AttributeSet attrs) {
        leftLayoutWidth = getScreenSize(getContext()).widthPixels;// recyclerview 宽度
        rightLayoutWidth = dp2px(getContext(),200);// 右边布局的宽度
        range = dp2px(getContext(), 30);// 移动多少开始切换阈值
        if (attrs!=null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRecyclerViewItem);
            int indexCount = typedArray.getIndexCount();
            for (int i = 0; i < indexCount; i++) {
                int index = typedArray.getIndex(i);
                if (index==R.styleable.MyRecyclerViewItem_left_width){
                    leftLayoutWidth = typedArray.getInteger(index, 0)==0? leftLayoutWidth : dp2px(context, typedArray.getInteger(index, 0));
                }
                if (index==R.styleable.MyRecyclerViewItem_right_width){
                    rightLayoutWidth = typedArray.getInteger(index, 0)==0? rightLayoutWidth : dp2px(context, typedArray.getInteger(index, 0));
                }
                if (index==R.styleable.MyRecyclerViewItem_move_range){
                    range = typedArray.getInteger(index, 0)==0? range : dp2px(context, typedArray.getInteger(index, 0));
                }
            }
            typedArray.recycle();
        }
    }

    //适配器 bind 方法中调用
    public void apply() {
        isLeft = true;
        changeLayout();
        scrollTo(0, 0);
    }

    private void changeLayout() {
        try {
            ViewGroup mainLayout= (ViewGroup) getChildAt(0);
            ViewGroup left= (ViewGroup) mainLayout.getChildAt(0);
            ViewGroup right= (ViewGroup) mainLayout.getChildAt(1);
            if (left.getMeasuredWidth()== leftLayoutWidth && right.getMeasuredWidth()==rightLayoutWidth){
                Log.i(TAG, "changeLayout: no change");
                return;
            }
            ViewGroup.LayoutParams layoutParams = left.getLayoutParams();
            layoutParams.width = leftLayoutWidth;
            left.setLayoutParams(layoutParams);
            ViewGroup.LayoutParams layoutParams2 = right.getLayoutParams();
            layoutParams2.width = rightLayoutWidth;
            left.setLayoutParams(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DisplayMetrics getScreenSize(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        return dm;
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            Log.i(getClass().getSimpleName(), "down");
            return true;
        }
        if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
            Log.i(getClass().getSimpleName(), "up");
            if (isLeft) {
                if (getScrollX() > range) {
                    isLeft = false;
                    smoothScrollTo(rightLayoutWidth, 0);
                } else {
                    smoothScrollTo(0, 0);
                }
            } else {
                if (getScrollX() < (rightLayoutWidth - range)) {
                    isLeft = true;
                    smoothScrollTo(0, 0);
                } else {
                    smoothScrollTo(rightLayoutWidth, 0);
                }
            }
            return true;
        }
        Log.i(getClass().getSimpleName(), "end");
        return super.onTouchEvent(ev);
    }


    public static int dp2px(Context context,float dpValue) {
        DisplayMetrics scale = context.getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, scale);
    }
}

四、调用测试

布局内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/insertLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

java代码:

package com.chenxing.searchjob.sdk.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chenxing.searchjob.sdk.base.activity.COMBaseActivity;

import io.rong.imkit.R;

public class TestClass extends COMBaseActivity {

    private String TAG = "IMListView";
    private RecyclerView recycler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.im_test_class);
        recycler=findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setAdapter(new MyApr());
    }

    public static class VH extends RecyclerView.ViewHolder{

        public TextView show;
        public TextView click;
        public MyRecyclerViewItem recyclerViewItem;

        public VH(View itemView) {
            super(itemView);
            recyclerViewItem=itemView.findViewById(R.id.scroll_item);
            show=itemView.findViewById(R.id.show);
            click=itemView.findViewById(R.id.click);
        }
    }

    public static class MyApr extends RecyclerView.Adapter<VH>{

        @Override
        public VH onCreateViewHolder(ViewGroup parent, int viewType) {
            return new VH(LayoutInflater.from(parent.getContext()).inflate(R.layout.im_test_item, parent, false));
        }

        @Override
        public void onBindViewHolder(final VH holder, final int position) {
            //恢复状态
            holder.recyclerViewItem.apply();
            holder.show.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(holder.itemView.getContext(), "编号:"+position, Toast.LENGTH_LONG).show();
                }
            });
            holder.click.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(holder.itemView.getContext(), "删除:"+position, Toast.LENGTH_LONG).show();
                }
            });
        }

        @Override
        public int getItemCount() {
            return 10;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


}

最简单侧滑菜单,因为他思路很容易理解,方便自己扩展调整,尤其布局调整很简单。
老鸟一看代码都不用我解释了。
对于新手这边解释一下;
主要是自定了item 的布局布局结构使用了HorizontalScrollView作为根节点;
每次bind时候计算一次尺寸进行布局,所以要调用apply 方法。
实现了touch处理事件,通过判断手指抬起的时候来处理滑动逻辑。
非常精简,RecyclerView 使用没有任何限制。
看完上面的左滑动 那么如果理解 右滑动菜单也是没有问题了!
如果对你有帮助请点点zan o

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
功能树形结构 RecyclerView支持滑动删除支持长按拖拽支持单个 view 点击或长按时拖拽可开启并更改滑动删除背景色可自由指定滑动删除和拖拽操作的方向展开关闭全部分组下载Demo:下载截图使用方法添加jitpack库//build.gradle(Project:)  allprojects {       repositories {     ...      maven { url 'https://www.jitpack.io' }      }     }添加依赖 //build.gradle(Module:)dependencies {    compile 'com.github.goweii:SwipeDragTreeRecyclerView:v1.2.0'  }在xml布局文件中使用官方RecyclerView<android.support.v7.widget.RecyclerView android:id="@ id/swipe_drag_tree_recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v7.widget.RecyclerView>继承 TreeState 增加几个静态变量,用于标识 item 的类别当然,你的数据应该存放在 TreeState 中public class TestTreeState extends TreeState {     public static final int TYPE_ONE = 1;     public static final int TYPE_TEO = 2;     public static final int TYPE_THREE = 3;     public static final int TYPE_FOUR = 4; }用你的 adapter 继承 BaseSwipeDragTreeAdapter 实现几个方法putTypeLayoutViewIds(int viewType, int layoutId, int[] viewIds, int[] clickFlags) 这4个参数的含义为:putTypeStartDragViewIds(int viewType, @IdRes int[] viewIds, int[] startDragFlags) 如果你想让某一个 view 在点击或者长按时实现拖拽,而不是在长按整个 item 时,应该调用这个方法完成配置viewType 类别 继承 TreeState 增加的静态变量layoutId 布局idviewIds 布局中需要用到的 view 的 idclickFlags 设置 view 是否需要点击事件,设置为 null 时默认不开启长按和单击, ClickFlag 为 adapter 的静态内部类,你直接使用即可viewType 布局类型viewIds 拖拽操作的 view 的 idstartDragFlags 拖拽标志,StartDragFlag 为 adapter 的静态内部类,你直接使用即可initIds() 在这个方法中你应该调用下面2个方法完成相关初始化bindData(BaseViewHolder holder, TypeData data) 你应该调用 holder.getItemViewType() 方法得到自定义的 item 的类别,依据类别判断 holder 绑定的数据类型,然后调用 holder 的 getView 方法获取 view 实例进行数据绑定public class TestBaseSwipeDragTreeAdapter extends BaseSwipeDragTreeAdapter {     private final int mOrientationType;     public TestBaseSwipeDragTreeAdapter(int orientationType) {         super();         mOrientationType = orientationType;     }     @Override     public void initIds() {         putTypeLayoutViewIds(TestTreeState.TYPE_ONE, R.layout.item1_swipe_drag_tree_recycler_view,                 new int[]{R.id.item1_sdtrv_tv}, null);         putTypeLayoutViewIds(TestTreeState.TYPE_TEO, R.layout.item2_swipe_drag_tree_recycler_view,                 new int[]{R.id.item2_sdtrv_tv}, null);         putTypeLayoutViewIds(TestTreeState.TYPE_THREE, R.layout.item3_swipe_drag_tree_recycler_view,                 new int[]{R.id.item3_sdtrv_tv}, null);         putTypeLayoutViewIds(TestTreeState.TYPE_FOUR, R.layout.item4_swipe_drag_tree_recycler_view,                 new int[]{R.id.item4_sdtrv_tv}, null);         putTypeLayoutViewIds(TestTreeState.TYPE_LEAF, R.layout.item5_swipe_drag_tree_recycler_view,                 new int[]{R.id.item5_sdtrv_tv}, null);         putTypeStartDragViewIds(TestTreeState.TYPE_ONE,                 new int[]{R.id.item1_sdtrv_tv}, null);         putTypeStartDragViewIds(TestTreeState.TYPE_TEO,                 new int[]{R.id.item2_sdtrv_tv}, null);         putTypeStartDragViewIds(TestTreeState.TYPE_THREE,                 new int[]{R.id.item3_sdtrv_tv}, null);         putTypeStartDragViewIds(TestTreeState.TYPE_FOUR,                 new int[]{R.id.item4_sdtrv_tv}, null);         putTypeStartDragViewIds(TestTreeState.TYPE_LEAF,                 new int[]{R.id.item5_sdtrv_tv}, null);     }     @Override     protected void bindData(BaseViewHolder holder, TypeData data) {         SwipeDragTreeViewHolder viewHolder = (SwipeDragTreeViewHolder) holder;         switch (holder.getItemViewType()) {             case TestTreeState.TYPE_ONE:                 TextView textView0 = (TextView) viewHolder.getView(R.id.item1_sdtrv_tv);                 textView0.setText((String) data.getData());                 break;             case TestTreeState.TYPE_TEO:                 TextView textView1 = (TextView) viewHolder.getView(R.id.item2_sdtrv_tv);                 textView1.setText((String) data.getData());                 break;             case TestTreeState.TYPE_THREE:                 TextView textView2 = (TextView) viewHolder.getView(R.id.item3_sdtrv_tv);                 textView2.setText((String) data.getData());                 break;             case TestTreeState.TYPE_FOUR:                 TextView textView3 = (TextView) viewHolder.getView(R.id.item4_sdtrv_tv);                 textView3.setText((String) data.getData());                 break;             case TestTreeState.TYPE_LEAF:                 TextView textView4 = (TextView) viewHolder.getView(R.id.item5_sdtrv_tv);                 textView4.setText((String) data.getData());                 break;             default:                 break;         }     } }在你的 activity 中调用 init() 方法为适配器绑定数据mSwipeDragTreeRecyclerView.setLayoutManager(getLayoutManager()); mSwipeDragTreeRecyclerView.setAdapter(mTestBaseSwipeDragTreeAdapter); mTestBaseSwipeDragTreeAdapter.init(mDatas);Adapter 相关方法说明init(ArrayList datas)给适配器绑定数据isMemoryExpandState()获取分组关闭后是否记忆子分组的展开状态setMemoryExpandState(boolean memoryExpandState)设置分组关闭后是否记忆子分组的展开状态isAllExpand()获取是否已经展开所有分组expandAll()展开所有分组collapseAll()关闭所有分组getPositions(int position)获取该 holder 位置所显示数据在树形结构数据中所处的位置setOnExpandChangeListener(OnExpandChangeListener onExpandChangeListener)设置 item 展开状态改变监听器notifyItemSwipe(int position)更新数据滑动删除,在监听器中调用更新数据notifyItemDrag(int currentPosition, int targetPosition)更新数据拖拽移动,在监听器中调用更新数据setOnItemSwipeListener(SwipeDragCallback.OnItemSwipeListener onItemSwipeListener)设置滑动删除监听器,应该调用 notifyItemSwipe 方法更新数据显示setOnItemDragListener(SwipeDragCallback.OnItemDragListener onItemDragListener)设置 item 拖拽监听器,应该调用 notifyItemDrag 方法更新数据显示setItemViewSwipeEnabled(boolean itemViewSwipeEnabled)设置开启关闭滑动删除setLongPressDragEnabled(boolean longPressDragEnabled)设置开启关闭长按拖拽setSwipeBackgroundColorEnabled(boolean swipeBackgroundColorEnabled)设置开启关闭滑动删除背景色isItemViewSwipeEnabled()获取是否开启滑动删除isLongPressDragEnabled()获取是否开启长按拖拽isSwipeBackgroundColorEnabled()获取是否开启滑动删除背景色setSwipeBackgroundColor(@ColorInt int swipeBackgroundColor)设置滑动删除背景色颜色setCustomSwipeFlag(int customSwipeFlag)设置可以滑动删除的方向,默认为垂直于滚动方向的2个方向setCustomDragFlag(int customDragFlag)设置可以拖拽的方向,线性布局默认为平行于滚动方向的2个方向,网格和流布局默认为上下左右4个方向都可以setOnItemViewClickListener(OnItemViewClickListener onItemViewClickListener)设置 itemView 点击监听器setOnItemViewLongClickListener(OnItemViewLongClickListener onItemViewLongClickListener)设置 itemView 长按监听器setOnCustomViewClickListener(OnCustomViewClickListener onCustomViewClickListener)设置 item 子 view 点击监听器,需要在适配器的 initIds() 方法中开启setOnCustomViewLongClickListener(OnCustomViewLongClickListener onCustomViewLongClickListener)设置 item 子 view 长按监听器,需要在适配器的 initIds() 方法中开启注意发现 bug 请联系 QQ302833254
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值