ItemTouchHelper类及RecyclerView的item滑动删除和拖拽案例

ItemTouchHelper类是v7包下的一个针对RecyclerView拖拽和滑动删除的辅助类,英文的解释:This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView.

下面用一个例子介绍一下:

先看效果图:
ItemTouchHelper类及RecyclerView的item滑动删除和拖拽案例_第1张图片


先介绍一下项目的结构图:
ItemTouchHelper类及RecyclerView的item滑动删除和拖拽案例_第2张图片


简要说明

helper文件夹中,是自己定义的接口和类,ItemTouchHelperAdapter和ItemTouchHelperViewHolder是需要RecyclerView.Adapter和RecyclerView.ViewHolder的子类去实现的。SimpleItemTouchHelperCallback继承了ItemTouchHelper.Callback,在SimpleItemTouchHelperCallback需要实现3个方法,分别是getMovementFlags(),onMove(),onSwiped()。

ItemTouchHelper.Callback中的几个方法

  • getMovementFlags():应该返回一个组合标志,它定义了在每个状态下启用的移动方向
    原文解释:Should return a composite flag which defines the enabled move directions in each state(idle, swiping, dragging).

  • onMove():当把之前的位置拖拽到新的位置上时调用
    原文解释: Called when ItemTouchHelper wants to move the dragged item from its old position to the new position.

  • onSwiped():当ViewHolder被用户滑动删除后调用。
    原文解释:Called when a ViewHolder is swiped by the user.

    -onChildDraw():在RecyclerView调用onDraw方法的时候,调用此方法
    原文解释:Called by ItemTouchHelper on RecyclerView’s onDraw callback
    可以在这个方法中,对itemView进行设置。如透明度,背景的变化等

  • onSelectedChanged():当item’touViewHolder拖拽或滑动
    原文解释:Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed.

  • clearView():当用户与itemview交互完且动画执行完,调用
    原文解释:Called by the ItemTouchHelper when the user interaction with an element is over and it also completed its animation.


将RecyclerView依附到ItemTouchHelper中

ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(mRecyclerView);

下面看具体代码:
helper文件夹中:

ItemTouchHelperAdapter接口

public interface ItemTouchHelperAdapter {
    void onItemMove(int fromPosition , int toPosition);
    void onItemDelete(int position);
}

ItemTouchHelperViewHolder接口

public interface ItemTouchHelperViewHolder {
    void onItemSelect();
    void onItemClear();
}

SimpleItemTouchHelperCallback

public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private static final float ALPHA_NORMAL = 1.0f;
    private ItemTouchHelperAdapter mAdapter;

    public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {

        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END;
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
        return 0;
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

        if (viewHolder.getItemViewType() != target.getItemViewType()) {
            return false;
        }

        mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());

        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemDelete(viewHolder.getAdapterPosition());
    }

    @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) {
            float alpha = ALPHA_NORMAL - Math.abs(dX) / viewHolder.itemView.getWidth();
            viewHolder.itemView.setAlpha(alpha);
            viewHolder.itemView.setTranslationX(dX);
        } else {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }

    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {

        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (viewHolder instanceof ItemTouchHelperViewHolder) {
                ItemTouchHelperViewHolder itemTouchHelperViewHolder = (ItemTouchHelperViewHolder) viewHolder;
                itemTouchHelperViewHolder.onItemSelect();
            }
        }

        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);

        viewHolder.itemView.setAlpha(ALPHA_NORMAL);

        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemTouchHelperViewHolder = (ItemTouchHelperViewHolder) viewHolder;
            itemTouchHelperViewHolder.onItemClear();
        }
    }
}

布局文件:

activity.xml

<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"
    tools:context="www.weshared.myitemtouchhelper.MainActivity">

    <FrameLayout
        android:id="@+id/fragment_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:visibility="visible" />

    <FrameLayout
        android:id="@+id/fragment_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:visibility="gone" />


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="20dp"
        android:src="@mipmap/list" />

RelativeLayout>

fragment.xml文件

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="www.weshared.myitemtouchhelper.MainActivity">

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

recycler_item文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/recycler_tv"
        android:textColor="@android:color/black"
        android:gravity="center"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="60dp" />

LinearLayout>

在MainActivity文件中:

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton fab;
    private boolean isList = true;
    private FragmentTransaction fragmentTransaction_list;
    private FragmentTransaction fragmentTransaction_grid;
    private ListFragment listFragment;
    private GridFragment gridFragment;
    private FrameLayout frameLayout_grid;
    private FrameLayout frameLayout_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initListener();
    }

    private void initView() {
        fab = (FloatingActionButton) findViewById(R.id.fab);
        frameLayout_list = (FrameLayout) findViewById(R.id.fragment_list);
        frameLayout_grid = (FrameLayout) findViewById(R.id.fragment_grid);
        listFragment = new ListFragment();
        gridFragment = new GridFragment();
        fragmentTransaction_list = getSupportFragmentManager().beginTransaction().replace(R.id.fragment_list, listFragment, "list");
        fragmentTransaction_list.commit();
        fragmentTransaction_grid = getSupportFragmentManager().beginTransaction().replace(R.id.fragment_grid, gridFragment, "grid");
        fragmentTransaction_grid.commit();
    }

    private void initListener() {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isList) {
                    frameLayout_list.setVisibility(View.GONE);
                    frameLayout_grid.setVisibility(View.VISIBLE);
                    fab.setImageResource(R.mipmap.grid);
                    isList = false;
                } else {
                    frameLayout_list.setVisibility(View.VISIBLE);
                    frameLayout_grid.setVisibility(View.GONE);
                    fab.setImageResource(R.mipmap.list);
                    isList = true;
                }
            }
        });
    }
}

ListFragment文件

public class ListFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager manager;
    private MyAdapter adapter;
    private ItemTouchHelper itemTouchHelper;
    private List mdatas = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        initData();
        initRecycler();
    }

    private void initData() {
        for (int i = 0; i < 30; i++) {
            mdatas.add("这是第" + i + "item");
        }
    }

    private void initRecycler() {

        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setHasFixedSize(true);
        adapter = new MyAdapter(getContext(), mdatas);
        mRecyclerView.setAdapter(adapter);

        //RecyclerView与ItemTouchHelper关联
        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
        itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView);
    }
}

GridFragment 文件与ListFragment基本相同,不相同的只有LayoutManager.

   //初始化的时候换成GridLayoutManager对象
   manager = new GridLayoutManager(getContext(),2);

MyAdapter文件

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements ItemTouchHelperAdapter {

    private Context mContext;
    private List mDatas = new ArrayList<>();

    public MyAdapter(Context context, List mdatas) {
        this.mContext = context;
        this.mDatas = mdatas;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_item, parent, false);

        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.textView.setText(mDatas.get(position));
    }

    @Override
    public int getItemCount() {
        if (null == mDatas) {
            return 0;
        }
        return mDatas.size();
    }

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        Collections.swap(mDatas, fromPosition, toPosition);
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onItemDelete(int position) {
        mDatas.remove(position);
        notifyItemRemoved(position);
    }

    class MyViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {

        TextView textView;

        public MyViewHolder(View itemView) {
            super(itemView);
            initView();
            initListener();
        }

        private void initView() {
            textView = (TextView) itemView.findViewById(R.id.recycler_tv);
        }

        private void initListener() {
            //事件监听
        }

        @Override
        public void onItemSelect() {
            itemView.setBackgroundColor(Color.LTGRAY);
        }

        @Override
        public void onItemClear() {
            itemView.setBackgroundColor(0);
        }
    }
}

你可能感兴趣的:(android提升)