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
    评论
### 回答1: 这个问题其实是一个编码问题。原本这个问句是“如何recyclerview侧滑删除item”,但是被编码转换了一下。如果要回答,应该是如下: 使用RecyclerView可以通过实现ItemTouchHelper.Callback类来实现侧滑删除item的效果。在实现ItemTouchHelper.Callback类中,可以通过onSwiped()方法实现侧滑删除item。在onSwiped()方法中,可以调用RecyclerView.Adapter的notifyItemRemoved()方法来通知RecyclerView移除该item。 ### 回答2: RecyclerViewAndroid上一个强大的列表控件。它提供了不同于ListView和GridView的Item视图回收机制以及更灵活的布局管理,同时也支持ItemTouchHelper类来实现方便的侧滑删除item的功能。 ItemTouchHelper是Android Support Library中为RecyclerView提供的一个辅助类,主要是用于支持RecyclerView中的拖拽和滑动事件。为了实现RecyclerView侧滑删除item的功能,我们需要使用ItemTouchHelper类,并实现ItemTouchHelper.Callback的各个方法(onMove、onSwiped等): 1. onMove():该方法用于处理RecyclerView中拖拽事件,通常用于实现Item的移动、排序等,我们可以在该方法中添加自己的代码,实现列表Item的移动。 2. onSwiped():该方法用于处理RecyclerView中的滑动事件,通常用于实现列表Item的删除等功能,我们可以在该方法中添加自己的代码,实现Item删除的操作。 在我们实现侧滑删除Item的过程中,上述两个方法都需要实现。其中,onSwiped()方法中,我们通常会使用adapter的remove()方法将Item从列表中移除。 具体实现过程如下: 1.创建一个SwipeToDeleteCallback类,并继承自ItemTouchHelper.Callback类。 public class SwipeToDeleteCallback extends ItemTouchHelper.Callback { //实现 onMove() 方法 @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } //实现 onSwiped() 方法 @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { //从数据源中移除 Item //adapter.remove(viewHolder.getAdapterPosition()) } //其他的实现方法... } 2.在onCreate()方法中创建SwipeToDeleteCallback实例,并将其绑定到RecyclerView上。 SwipeToDeleteCallback swipeHandler = new SwipeToDeleteCallback(this); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipeHandler); itemTouchHelper.attachToRecyclerView(recyclerView); 3.在RecyclerView的Adapter中实现remove()方法,并在onBindViewHolder()方法中为每个Item添加GestureDetector。通过监听GestureDetector的滑动事件,判断当前Item是否向右滑动,并根据滑动的方向调用ItemTouchHelper.Callback的onSwiped()方法。 public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { //数据源 List<String> mDataList = new ArrayList<>(); //添加Item操作 public void addItem(String item) { mDataList.add(item); notifyItemInserted(mDataList.size() - 1); } //移除 Item 操作 public void remove(int position) { mDataList.remove(position); notifyItemRemoved(position); } // 创建 ViewHolder @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { //创建 Item 布局 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); return new ViewHolder(view); } // 绑定 ViewHolder @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { //设置 Item 数据 holder.itemText.setText(mDataList.get(position)); //添加 GestureDetector 监听 Item 滑动事件 GestureDetectorCompat gestureDetector = new GestureDetectorCompat(holder.itemView.getContext(), new MyGestureListener(holder)); holder.itemView.setOnTouchListener((view, motionEvent) -> { gestureDetector.onTouchEvent(motionEvent); return true; }); } //获取数据源大小 @Override public int getItemCount() { return mDataList.size(); } //创建 ViewHolder static class ViewHolder extends RecyclerView.ViewHolder { private TextView itemText; ViewHolder(View itemView) { super(itemView); itemText = itemView.findViewById(R.id.item_text); } } //GestureDetector 监听器,用于监听 Item 的滑动事件 class MyGestureListener extends GestureDetector.SimpleOnGestureListener { private final ViewHolder mHolder; MyGestureListener(MyAdapter.ViewHolder holder) { mHolder = holder; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { final float xDiff = e2.getX() - e1.getX(); if (Math.abs(xDiff) > 100) { //向右滑动时调用 onSwiped()方法 if (xDiff > 0) { remove(mHolder.getAdapterPosition()); return true; } } return false; } } } 在上述功能实现过程中,我们继承了ItemTouchHelper.Callback来自定义每个Item的拖拽和滑动事件,使用ItemTouchHelper将这个Callback实例与RecyclerView绑定在一起,然后在Adapter中添加了remove()方法,以实现Item的删除功能。最後,我们使用GestureDetector监听Item滑动事件,并根据滑动的方向调用ItemTouchHelper.Callback的onSwiped()方法。 在实现RecyclerView侧滑删除item的过程中,我们还可以对ItemView进行进一步的美化,例如在ItemView左右两侧添加删除和修改按钮等。总之,RecyclerView提供了足够灵活的机制,使得我们能够自由地扩展和定制列表控件的各种功能,为用户提供优秀的使用体验。 ### 回答3: RecyclerViewAndroid官方推出的一个列表控件,它比ListView具有更为灵活和高效的特性,支持数据动态更新、多种布局管理、 ItemTouchHelper操作等,而其支持的滑动操作也极大地方便了用户操作列表数据。针对RecyclerView侧滑删除item,可以通过以下方式实现。 1. ItemTouchHelper ItemTouchHelper是RecyclerView的内置工具类,可实现滑动删除、拖曳排序等操作。通过ItemTouchHelper.onSwiped()回调将删除数据源,再通过适配器的notifyItemRemoved()通知RecyclerView删除某个条目。 2. 自定义ItemDecoration 我们可以通过RecyclerView的ItemDecoration来实现侧滑删除操作,通过自定义一个类继承ItemDecoration并在其onDraw()方法中绘制删除按钮,再通过onTouchEvent()方法实现删除操作,即可实现侧滑删除item。 3. 第三方库 目前市面上也有一些优秀的RecyclerView侧滑删除第三方库,如SwipeMenuRecyclerView、SwipeRecyclerView等。这些库都提供了美观且易于使用的侧滑删除控件,大大降低了开发者的工作量。 总之,RecyclerView侧滑删除功能符合用户的使用习惯,提高了用户的操作效率,是不可或缺的一个功能,希望开发者在设计列表页面时能够注重用户体验,添加RecyclerView侧滑删除功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值