可滑动删除的Listview:EnhancedListView

open_gly 8年前

 android自带的下拉通知幕帘和谷歌记事google keep的listview都有一个共同的效果,左右滑动可删除listView,虽然实际使用中对这种效果的需求不是刚需,但能实现也是非常酷的。

github上有这种效果的开源代码EnhancedListView,项目地址:https://github.com/timroes/EnhancedListView

使用方法跟一般的控件一下,在xml中使用<de.timroes.android.listview.EnhancedListView>来表明是EnhancedListView控件,然后加上应该有的属性。

除了滑动删除效果之外,该控件还有个撤销功能,能撤销上一步的滑动删除操作。

1.滑动删除

你需要调用enableSwipeToDismiss()来设置滑动删除可用,默认左右均可滑动,setSwipeDirection()方法可以限制滑动的方向。默认,一次滑动真个listview的Item都会滑动,如果你想Item只是一部分跟着滑动,可以调用setSwipeLayout()方法,并且将需要滑动的View的id作为参数传递给他。

如果你只想滑动部分item,而不是每个item都能滑动,则可以在OnShouldSwipeCallback方法中指定,这种情况发生在当listview有headerview的时候,比如下面的代码实现了只滑动偶数item:

 

mListView.setShouldSwipeCallback(new OnShouldSwipeCallback() {    @Override    public boolean onShouldSwipe(EnhancedListView lv, int position) {      // Only allow even items to be swiped (for whatever reason)      return position % 2 == 0;    }  });

OnShouldSwipeCallback中onShouldSwipe()方法return true则表示该item可滑动,否则为不可滑动。

在默认情况下,当你滑动了至少32dip距离的时候,滑动效果才会开始,如果你想改变这个值,可以在app的dimen文件中增加elv_touch_slop来覆盖默认的值。

2.撤销

EnhancedListView提供了在滑动删除之后还能撤销这种行为的方法,需要创建一个EnhancedListView.OnDismissCallback回调对象,并且将其传递给EnhancedListView.setDismissCallback,如果你删除item之前调用setDismissCallback,则会发生IllegalStateException异常。

// mAdapter if your adapter, that has already been initialized and set to the listview.  setDismissCallback(new OnDismissCallback() {    @Override public EnhancedListView.Undoable onDismiss(EnhancedListView listView, final int position) {      // Store the item for later undo      final Person item = (Person) mAdapter.getItem(position);      // Remove the item from the adapter      mAdapter.remove(position);      // return an Undoable      return new EnhancedListView.Undoable() {        // Reinsert the item to the adapter        @Override public void undo() {          mAdapter.insert(position, item);        }        // Return a string for your item        @Override public String getTitle() {          return "Deleted '" + item.getFullName() . "'"; // Plz, use the resource system :)        }        // Delete item completely from your persistent storage        @Override public void discard() {          MyDatabasUtils.delete(item);        }      };    }  });