简体   繁体   中英

Android 5 RecyclerView like Gmail

I was playing with RecyclerView, and I found that there not much document on how to play with it

I see from the document that the GMail application is using RecyclerView, but in the application it has lots of features that a normal RecyclerView doesnt support:

There is a screenshot from it

https://developer.android.com/training/material/lists-cards.html

Features:

  1. List item highlight when onTouch
  2. Swipe left/right to delete

May I know how to implement these features?

I found there is a discussion on how to implement OnClickListener, (thou these solution is quite sluggish, because it constantly checks for the list item region)

RecyclerView onClick

But, if you compare it with the Gmail application, it is fast and fluid!

May I know how can I implement the 2 features above? How do they do it? are they using Recyclerview or ListView?

I am sure I could implement those features using ListView, but I have no idea how to implement them using Recyclerview.

Swipe left/right can be performed that way: Swipe with ItemTouchHelper - jmcdale's answer

SwipeToDismiss available out of the box from Android support library.

  1. Add 'recyclerview-v7:22.2.+' dependence to build.gradle:

    compile 'com.android.support:recyclerview-v7:22.2.+'

  2. Add remove method to your RecyclerView.Adapter implementation:

     public class ExampleAdapter extends Adapter<ExampleItem> { [...] public void remove(int position) { list.remove(position); notifyItemRemoved(position); } } 
  3. Use ItemTouchHelper and ItemTouchHelper.Callback:

     ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { //Remove swiped item adapter.remove(viewHolder.getAdapterPosition()) } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { //Available drag and drop directions int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; //Available swipe directions int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; return makeMovementFlags(dragFlags, swipeFlags); } //Disable or Enable drag and drop by long press @Override public boolean isLongPressDragEnabled() { //return false; return true; } //Disable or Enable swiping @Override public boolean isItemViewSwipeEnabled() { //return false; return true; } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); 
  4. Attach ItemTouchHelper to RecyclerView

     itemTouchHelper.attachToRecyclerView(recyclerView); 

Another useful link: Drag and swipe with recyclerView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM