1. 程式人生 > >RecyclerView實現條目拖拽,左滑、右滑移除效果

RecyclerView實現條目拖拽,左滑、右滑移除效果

對於android開發者來說RecyclerView應該已經很熟悉了,專案中基本都是使用RecyclerView來實現列表效果,這裡要實現的是RecyclerView的條目拖拽、左滑、右滑移除效果,這些效果都是在RecyclerView列表基礎上來實現的,所以還是先簡單的實現RecyclerView的列表效果;

一開始肯定要引入依賴庫:

compile 'com.android.support:recyclerview-v7:25.3.1'

接下來在xml佈局檔案中使用同時通過findViewById在activity檔案中引入;

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.qqrecyclerview.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>
public class MainActivity extends AppCompatActivity{
    private RecyclerView recyclerView;
    private MessageAdapter adapter;
    private ItemTouchHelper itemTouchHelper;
    private List<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = DataUtils.getData();
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        //設定佈局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //設定介面卡
        adapter = new MessageAdapter(this, list, this);
        recyclerView.setAdapter(adapter); 
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClickListener(int position) {
                Toast.makeText(MainActivity.this, list.get(position), Toast.LENGTH_LONG).show();
            }
        });
    }
}

這裡關鍵在與介面卡了;

package com.qqrecyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2017/12/25.
 */

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHolder>{
    private Context context;
    private List<String> list;
    private StartDragLinstener startDragLinstener;
    public MessageAdapter(Context context, List<String> list, StartDragLinstener startDragLinstener) {
        this.context = context;
        this.list = list;
        this.startDragLinstener = startDragLinstener;
    }

    @Override
    public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.message_item, parent, false);
        MessageHolder holder = new MessageHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(final MessageHolder holder, final int position) {
        holder.tv.setText(list.get(position));
        holder.iv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //傳遞事件
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (startDragLinstener != null) {
                        startDragLinstener.onStartDrag(holder);
                    }
                }
                //如果想攔截imageview的點選事件return true就可以了
                return false;
            }
        });
        /**
         * 條目點選
         */
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onItemClickListener(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }
    class MessageHolder extends RecyclerView.ViewHolder {
        TextView tv;
        ImageView iv;

        public MessageHolder(View itemView) {
            super(itemView);
            tv = (TextView) itemView.findViewById(R.id.tv);
            iv = (ImageView) itemView.findViewById(R.id.iv);
        }
    }
    private OnItemClickListener listener;

    /**
     * 條目點選
     * @param listener
     */
    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener=listener;
    }
}

RecyclerView的介面卡和ListView的介面卡有很大的不同,RecyclerView的介面卡需要重寫onCreateViewHolder(),onBindViewHolder(),getItemCount(),三個方法,通過每個方法的含義就能知道每個方法對應的功能實現,除此之外還要建立一個ViewHolder物件,不過RecyclerView並沒實現條目的點選和長按等事件的處理,都知道RecyclerView只負責資料的載入和複用回收,這裡利用介面回撥的方式來實現條目點選的,長按等事件的實現也可仿照其實現;

/**
 * Created by Administrator on 2017/12/26.
 * RecylerView條目點選
 */

public interface OnItemClickListener {
    void onItemClickListener(int position);
}


普通列表效果就實現了,在上面的基礎上慢慢的去實現條目拖拽和左滑、右滑等效果;

系統提供了ItemTouchHelper類可以輕鬆的實現條目拖拽和左滑、右滑等效果;在activity中先將ItemTouchHelper類和RecyclerView繫結關係;

//例項化ItemTouchHelper
itemTouchHelper = new ItemTouchHelper(new MessageItemTouchCallBack(adapter));
//將ItemTouchHelper和RecyclerView進行關聯
itemTouchHelper.attachToRecyclerView(recyclerView);

ItemTouchHelper例項化的時候需要傳入一個Callback的抽象類,MessageItemTouchCallBack類是Callback的子類,在MessageItemTouchCallBack在構造方法中需要傳入一個ItemTouchHelperAdapterCallBack介面,而MessageAdapter類實現了ItemTouchHelperAdapterCallBack介面,所以出入一個MessageAdapter就可以了;
public class MessageItemTouchCallBack extends ItemTouchHelper.Callback {
    private ItemTouchHelperAdapterCallBack adapterCallBack;

    public MessageItemTouchCallBack(ItemTouchHelperAdapterCallBack adapterCallBack) {
        this.adapterCallBack = adapterCallBack;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        //callback回撥監聽哪些動作,判斷方向(水平方向,垂直方向)
        //垂直方向
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        //水平方向
        int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        //監聽滑動(水平方向,垂直方向)
        //將集合中的兩個資料進行位置互動
        //同時還要重新整理RecyclerView
        adapterCallBack.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return false;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        //滑動刪除的動作的時候回撥
        //刪除資料集合裡面的direction位置的資料
        //重新整理adapter
        adapterCallBack.onItemSwiped(viewHolder, viewHolder.getAdapterPosition());
    }

    @Override
    public boolean isLongPressDragEnabled() {
        //長按拖動是否開啟
        return true;
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        //實現動畫
        //側滑動作
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            swipedItem(dX, viewHolder);
        }
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    /**
     * 新增側滑刪除動作動畫效果
     *
     * @param dX
     * @param viewHolder
     */
    private void swipedItem(float dX, RecyclerView.ViewHolder viewHolder) {
        float alpha = 1 - Math.abs(dX) / viewHolder.itemView.getWidth();
        //透明度動畫
        viewHolder.itemView.setAlpha(alpha);
        //X縮放動畫
        viewHolder.itemView.setScaleX(Math.max(0.6f, alpha));
        //Y縮放動畫
        viewHolder.itemView.setScaleY(Math.max(0.6f, alpha));
        if (alpha == 0) {
            //代表滑出去了
            viewHolder.itemView.setAlpha(1);
            viewHolder.itemView.setScaleX(1);
            viewHolder.itemView.setScaleY(1);
        }
    }
}
每個方法都做了說明,在這裡拖拽或者移除時要將其回撥到RecyclerView的介面卡中,方便資料的處理;剛好 MessageAdapter類實現了 ItemTouchHelperAdapterCallBack介面,就會重寫onItemMove和onItemSwiped方法;
/**
 * Created by Administrator on 2017/12/26.
 */

public interface ItemTouchHelperAdapterCallBack {
    /**
     * 當拖拽的時候回撥
     * @param fromPosition  開始觸控位置
     * @param toPosition  目標位置
     * @return
     */
    boolean onItemMove(int fromPosition,int toPosition);

    /**
     * 左右滑動刪除的時候回撥
     * @param toPosition  滑動的位置
     */
    void onItemSwiped(RecyclerView.ViewHolder holder,int toPosition);
}
ItemTouchHelperAdapterCallBack介面提供的方法;
@Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        //將集合中的兩個資料進行位置互動
        Collections.swap(list, fromPosition, toPosition);
        //同時還要重新整理RecyclerView
        notifyItemMoved(fromPosition, toPosition);
        return false;
    }

    @Override
    public void onItemSwiped(RecyclerView.ViewHolder holder, int toPosition) {
        //刪除資料集合裡面的direction位置的資料
        list.remove(toPosition);
        //重新整理adapter
        notifyItemRemoved(toPosition);
    }
還有一個比較重要的就是在例項化adapter的時候傳入一個StartDragLinstener介面;
/**
 * Created by Administrator on 2017/12/26.
 */

public interface StartDragLinstener {
    void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
在重寫onStartDrag方法的時候需要呼叫ItemTouchHelper中的startDrag方法,才能夠去觸發拖拽,移除等方法;
@Override
    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
        //呼叫startDrag方法後就會去回撥onSwiped()方法
        itemTouchHelper.startDrag(viewHolder);
    }
這樣子就實現了一個比較簡單的RecyclerView的條目拖拽、左滑、右滑移除效果了; 原始碼地址: https://pan.baidu.com/s/1o9O6iyY