Android RecyclerView 滑动删除例子

戏子无情 提交于 2019-11-29 11:55:59

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xiexuan2007/article/details/53156916
效果图

1.自定义Item容器View,SlidingButtonView.java
package com.android.mx.myapplication;
 
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
 
/**
 * Created by Administrator on 2016-11-11.
 */
public class SlidingButtonView extends HorizontalScrollView {
 
    private TextView mTextView_Delete;
 
    private int mScrollWidth;
 
    private IonSlidingButtonListener mIonSlidingButtonListener;
 
    private Boolean isOpen = false;
    private Boolean once = false;
 
 
    public SlidingButtonView(Context context) {
        this(context, null);
    }
 
    public SlidingButtonView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
 
    public SlidingButtonView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
 
        this.setOverScrollMode(OVER_SCROLL_NEVER);
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 
        if(!once){
            mTextView_Delete = (TextView) findViewById(R.id.tv_delete);
            once = true;
        }
 
    }
 
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if(changed){
            this.scrollTo(0,0);
            //获取水平滚动条可以滑动的范围,即右侧按钮的宽度
            mScrollWidth = mTextView_Delete.getWidth();
            Log.i("asd", "mScrollWidth:" + mScrollWidth);
        }
 
    }
 
 
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                mIonSlidingButtonListener.onDownOrMove(this);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                changeScrollx();
                return true;
            default:
                break;
        }
        return super.onTouchEvent(ev);
    }
 
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        mTextView_Delete.setTranslationX(l - mScrollWidth);
    }
 
    /**
     * 按滚动条被拖动距离判断关闭或打开菜单
     */
    public void changeScrollx(){
        if(getScrollX() >= (mScrollWidth/2)){
            this.smoothScrollTo(mScrollWidth, 0);
            isOpen = true;
            mIonSlidingButtonListener.onMenuIsOpen(this);
        }else{
            this.smoothScrollTo(0, 0);
            isOpen = false;
        }
    }
 
    /**
     * 打开菜单
     */
    public void openMenu()
    {
        if (isOpen){
            return;
        }
        this.smoothScrollTo(mScrollWidth, 0);
        isOpen = true;
        mIonSlidingButtonListener.onMenuIsOpen(this);
    }
 
    /**
     * 关闭菜单
     */
    public void closeMenu()
    {
        if (!isOpen){
            return;
        }
        this.smoothScrollTo(0, 0);
        isOpen = false;
    }
 
 
 
 
    public void setSlidingButtonListener(IonSlidingButtonListener listener){
        mIonSlidingButtonListener = listener;
    }
 
    public interface IonSlidingButtonListener{
        void onMenuIsOpen(View view);
        void onDownOrMove(SlidingButtonView slidingButtonView);
    }
 
 
}
2.定义每个Item的XML,layout_item.xml
<com.android.mx.myapplication.SlidingButtonView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginBottom="1dp"
    android:background="@android:color/white">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <TextView
            android:id="@+id/tv_delete"
            android:layout_width="160dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/layout_content"
            android:background="@drawable/btn_click_red_havebackground"
            android:gravity="center"
            android:text="删 除"
            android:textColor="#DDFFFFFF" />
 
        <RelativeLayout
            android:id="@+id/layout_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
 
            <TextView
                android:id="@+id/text"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_click_black_havebackground"
                android:textColor="#DD000000"
                android:textSize="50dp" />
        </RelativeLayout>
 
    </RelativeLayout>
</com.android.mx.myapplication.SlidingButtonView>


3定义Adapter,Adapter.java
package com.android.mx.myapplication;
 
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by Administrator on 2016-11-11.
 */
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements SlidingButtonView.IonSlidingButtonListener {
    private Context mContext;
 
    private IonSlidingViewClickListener mIDeleteBtnClickListener;
 
    private List<String> mDatas = new ArrayList<String>();
 
    private SlidingButtonView mMenu = null;
 
    public Adapter(Context context) {
 
        mContext = context;
        mIDeleteBtnClickListener = (IonSlidingViewClickListener) context;
 
        for (int i = 0; i < 10; i++) {
            mDatas.add(i + "");
        }
    }
 
    @Override
    public int getItemCount() {
        return mDatas.size();
    }
 
    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
 
        holder.textView.setText(mDatas.get(position));
        //设置内容布局的宽为屏幕宽度
        holder.layout_content.getLayoutParams().width = Utils.getScreenWidth(mContext);
 
        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有删除菜单打开
                if (menuIsOpen()) {
                    closeMenu();//关闭菜单
                } else {
                    int n = holder.getLayoutPosition();
                    mIDeleteBtnClickListener.onItemClick(v, n);
                }
 
            }
        });
        holder.btn_Delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int n = holder.getLayoutPosition();
                mIDeleteBtnClickListener.onDeleteBtnCilck(v, n);
            }
        });
    }
 
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
 
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_item, arg0, false);
        MyViewHolder holder = new MyViewHolder(view);
 
        return holder;
    }
 
    public void addData(int position) {
        mDatas.add(position, "添加项");
        notifyItemInserted(position);
    }
 
    public void removeData(int position) {
        mDatas.remove(position);
        notifyItemRemoved(position);
 
    }
 
    /**
     * 删除菜单打开信息接收
     */
    @Override
    public void onMenuIsOpen(View view) {
        mMenu = (SlidingButtonView) view;
    }
 
    /**
     * 滑动或者点击了Item监听
     *
     * @param slidingButtonView
     */
    @Override
    public void onDownOrMove(SlidingButtonView slidingButtonView) {
        if (menuIsOpen()) {
            if (mMenu != slidingButtonView) {
                closeMenu();
            }
        }
    }
 
    /**
     * 关闭菜单
     */
    public void closeMenu() {
        mMenu.closeMenu();
        mMenu = null;
 
    }
 
    /**
     * 判断是否有菜单打开
     */
    public Boolean menuIsOpen() {
        if (mMenu != null) {
            return true;
        }
        return false;
    }
 
    public interface IonSlidingViewClickListener {
        void onItemClick(View view, int position);
 
        void onDeleteBtnCilck(View view, int position);
    }
 
    class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView btn_Delete;
        public TextView textView;
        public ViewGroup layout_content;
 
        public MyViewHolder(View itemView) {
            super(itemView);
            btn_Delete = (TextView) itemView.findViewById(R.id.tv_delete);
            textView = (TextView) itemView.findViewById(R.id.text);
            layout_content = (ViewGroup) itemView.findViewById(R.id.layout_content);
 
            ((SlidingButtonView) itemView).setSlidingButtonListener(Adapter.this);
        }
    }
}

4定义相关的Utils,Utils.java
package com.android.mx.myapplication;
 
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;
 
public class Utils {
 
    //屏幕宽度(像素)
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
}

5使用效果,MainActivity.java,activity_main.xml
MainActivity.java
package com.android.mx.myapplication;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
 
public class MainActivity extends AppCompatActivity implements Adapter.IonSlidingViewClickListener {
    private final String TAG = "test";
    private RecyclerView mRecyclerView;
    private Adapter mAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        initView();
        setAdapter();
 
    }
 
    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    }
 
    private void setAdapter() {
 
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter = new Adapter(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
 
    }
 
    @Override
    public void onItemClick(View view, int position) {
        Log.i(TAG, "点击项:" + position);
    }
 
    @Override
    public void onDeleteBtnCilck(View view, int position) {
        Log.i(TAG, "删除项:" + position);
        mAdapter.removeData(position);
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.android.mx.myapplication.MainActivity">
 
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:background="#EEEEEE"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:overScrollMode="never"
        />
</RelativeLayout>

在build.gradle中应用
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:recyclerview-v7:22.2.1'

————————————————
版权声明:本文为CSDN博主「xiexuan2007」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xiexuan2007/article/details/53156916

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!