http://blog.csdn.net/xiaanming/article/details/17539199
先说下实现该效果的主要思路
- 先根据手指触摸的点来获取点击的是ListView的哪一个item
- 手指在屏幕中滑动我们利用scrollBy()来使该item跟随手指一起滑动
- 手指放开的时候,我们判断手指拖动的距离来判断item到底是滑出屏幕还是回到开始位置
主要思路就是上面这三步,接下来我们就用代码来实现吧,首先我们新建一个项目,叫SlideCutListView
根据需求我们需要自己自定义一个ListView来实现该功能,接下来先贴出代码再讲解具体的实现
- package com.example.slidecutlistview;
-
- import android.content.Context;
- import android.util.AttributeSet;
- import android.view.MotionEvent;
- import android.view.VelocityTracker;
- import android.view.View;
- import android.view.ViewConfiguration;
- import android.view.WindowManager;
- import android.widget.AdapterView;
- import android.widget.ListView;
- import android.widget.Scroller;
-
-
-
-
-
-
-
- public class SlideCutListView extends ListView {
-
-
-
- private int slidePosition;
-
-
-
- private int downY;
-
-
-
- private int downX;
-
-
-
- private int screenWidth;
-
-
-
- private View itemView;
-
-
-
- private Scroller scroller;
- private static final int SNAP_VELOCITY = 600;
-
-
-
- private VelocityTracker velocityTracker;
-
-
-
- private boolean isSlide = false;
-
-
-
- private int mTouchSlop;
-
-
-
- private RemoveListener mRemoveListener;
-
-
-
- private RemoveDirection removeDirection;
-
-
- public enum RemoveDirection {
- RIGHT, LEFT;
- }
-
-
- public SlideCutListView(Context context) {
- this(context, null);
- }
-
- public SlideCutListView(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public SlideCutListView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- screenWidth = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
- scroller = new Scroller(context);
- mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
- }
-
-
-
-
-
- public void setRemoveListener(RemoveListener removeListener) {
- this.mRemoveListener = removeListener;
- }
-
-
-
-
- @Override
- public boolean dispatchTouchEvent(MotionEvent event) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN: {
- addVelocityTracker(event);
-
-
- if (!scroller.isFinished()) {
- return super.dispatchTouchEvent(event);
- }
- downX = (int) event.getX();
- downY = (int) event.getY();
-
- slidePosition = pointToPosition(downX, downY);
-
-
- if (slidePosition == AdapterView.INVALID_POSITION) {
- return super.dispatchTouchEvent(event);
- }
-
-
- itemView = getChildAt(slidePosition - getFirstVisiblePosition());
- break;
- }
- case MotionEvent.ACTION_MOVE: {
- if (Math.abs(getScrollVelocity()) > SNAP_VELOCITY
- || (Math.abs(event.getX() - downX) > mTouchSlop && Math
- .abs(event.getY() - downY) < mTouchSlop)) {
- isSlide = true;
- }
- break;
- }
- case MotionEvent.ACTION_UP:
- recycleVelocityTracker();
- break;
- }
-
- return super.dispatchTouchEvent(event);
- }
-
-
-
-
- private void scrollRight() {
- removeDirection = RemoveDirection.RIGHT;
- final int delta = (screenWidth + itemView.getScrollX());
-
- scroller.startScroll(itemView.getScrollX(), 0, -delta, 0,
- Math.abs(delta));
- postInvalidate();
- }
-
-
-
-
- private void scrollLeft() {
- removeDirection = RemoveDirection.LEFT;
- final int delta = (screenWidth - itemView.getScrollX());
-
- scroller.startScroll(itemView.getScrollX(), 0, delta, 0,
- Math.abs(delta));
- postInvalidate();
- }
-
-
-
-
- private void scrollByDistanceX() {
-
- if (itemView.getScrollX() >= screenWidth / 3) {
- scrollLeft();
- } else if (itemView.getScrollX() <= -screenWidth / 3) {
- scrollRight();
- } else {
-
- itemView.scrollTo(0, 0);
- }
-
- }
-
-
-
-
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- if (isSlide && slidePosition != AdapterView.INVALID_POSITION) {
- addVelocityTracker(ev);
- final int action = ev.getAction();
- int x = (int) ev.getX();
- switch (action) {
- case MotionEvent.ACTION_MOVE:
- int deltaX = downX - x;
- downX = x;
-
-
- itemView.scrollBy(deltaX, 0);
- break;
- case MotionEvent.ACTION_UP:
- int velocityX = getScrollVelocity();
- if (velocityX > SNAP_VELOCITY) {
- scrollRight();
- } else if (velocityX < -SNAP_VELOCITY) {
- scrollLeft();
- } else {
- scrollByDistanceX();
- }
-
- recycleVelocityTracker();
-
- isSlide = false;
- break;
- }
-
- return true;
- }
-
-
- return super.onTouchEvent(ev);
- }
-
- @Override
- public void computeScroll() {
-
- if (scroller.computeScrollOffset()) {
-
- itemView.scrollTo(scroller.getCurrX(), scroller.getCurrY());
-
- postInvalidate();
-
-
- if (scroller.isFinished()) {
- if (mRemoveListener == null) {
- throw new NullPointerException("RemoveListener is null, we should called setRemoveListener()");
- }
-
- itemView.scrollTo(0, 0);
- mRemoveListener.removeItem(removeDirection, slidePosition);
- }
- }
- }
-
-
-
-
-
-
- private void addVelocityTracker(MotionEvent event) {
- if (velocityTracker == null) {
- velocityTracker = VelocityTracker.obtain();
- }
-
- velocityTracker.addMovement(event);
- }
-
-
-
-
- private void recycleVelocityTracker() {
- if (velocityTracker != null) {
- velocityTracker.recycle();
- velocityTracker = null;
- }
- }
-
-
-
-
-
-
- private int getScrollVelocity() {
- velocityTracker.computeCurrentVelocity(1000);
- int velocity = (int) velocityTracker.getXVelocity();
- return velocity;
- }
-
-
-
-
-
-
-
-
-
- public interface RemoveListener {
- public void removeItem(RemoveDirection direction, int position);
- }
-
- }
- 首先我们重写dispatchTouchEvent()方法,该方法是事件的分发方法,我们在里面只做了一些简单的步骤,我们按下屏幕的时候,如果某个item正在进行滚动,我们直接交给SlideCutListView的父类处理分发事件,否则根据点击的X,Y坐标利用pointToPosition(int x, int y)来获取点击的是ListView的哪一个position,从而获取到我们需要滑动的item的View,我们还在该方法加入了滑动速度的检测,并且在ACTION_MOVE的时候来判断是否响应item的左右移动,用isSlide来记录是否响应左右滑动
- 然后就是重写onTouchEvent()方法,我们先判断isSlide为true,并且我们点击的是ListView上面的有效的position,否则直接交给SlideCutListView的父类也就是ListView来处理,在ACTION_MOVE中调用scrollBy()来移动item,scrollBy()是相对item的上一个位置进行移动的,所以我们每次都要用现在移动的距离减去上一个位置的距离然后赋给scrollBy()方法,这样子我们就实现了item的平滑移动,当我们将手指抬起的时候,我们先根据手指滑动的速度来确定是item是滑出屏幕还是滑动至原始位置,如果向右的速度大于我们设置的SNAP_VELOCITY,item就调用scrollRight()方法滚出屏幕,如果向左的速度小于-SNAP_VELOCITY,则调用scrollLeft()向左滚出屏幕,如果我们是缓慢的移动item,则调用scrollByDistanceX()方法来判断是滚到那个位置
在scrollRight()和scrollLeft()方法中我们使用Scroller类的startScroll()方法先设置滚动的参数,然后调用postInvalidate()来刷新界面,界面刷新就会调用computeScroll()方法,我们在里面处理滚动逻辑就行了,值得一提的是computeScroll()里面的这段代码
我们需要将该item滚动在(0, 0 )这个点,因为我们只是将ListView的Item滚动出屏幕而已,并没有将该item移除,而且我们不能手动调用removeView()来从ListView中移除该item,我们只能通过改变ListView的数据,然后通过notifyDataSetChanged()来刷新ListView,所以我们需要将其滚动至(0, 0),这里比较关键。
定义好了我们左右滑动的ListView,接下来就来使用它,布局很简单,一个RelativeLayout包裹我们自定义的ListView
- <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:background="@android:color/darker_gray">
-
- <com.example.slidecutlistview.SlideCutListView
- android:id="@+id/slideCutListView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:listSelector="@android:color/transparent"
- android:divider="@drawable/reader_item_divider"
- android:cacheColorHint="@android:color/transparent">
- </com.example.slidecutlistview.SlideCutListView>
-
- </RelativeLayout>
接下来我们来看看ListView的item的布局
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@drawable/friendactivity_comment_detail_list2" >
-
- <TextView
- android:id="@+id/list_item"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_margin="15dip" />
- </LinearLayout>
-
- </LinearLayout>
还记得我在上一篇文章中提到过调用scrollTo()方法是对里面的子View进行滚动的,而不是对整个布局进行滚动的,所以我们用LinearLayout来套住我们的item的布局,这点需要注意一下,不然滚动的只是TextView。
主页面MainActivity里面的代码比较简单,里面使用的也是ArrayAdapter,相信大家都能看懂
- package com.example.slidecutlistview;
-
- import java.util.ArrayList;
- import java.util.List;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.ArrayAdapter;
- import android.widget.Toast;
-
- import com.example.slidecutlistview.SlideCutListView.RemoveDirection;
- import com.example.slidecutlistview.SlideCutListView.RemoveListener;
-
- public class MainActivity extends Activity implements RemoveListener{
- private SlideCutListView slideCutListView ;
- private ArrayAdapter<String> adapter;
- private List<String> dataSourceList = new ArrayList<String>();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- init();
- }
-
- private void init() {
- slideCutListView = (SlideCutListView) findViewById(R.id.slideCutListView);
- slideCutListView.setRemoveListener(this);
-
- for(int i=0; i<20; i++){
- dataSourceList.add("滑动删除" + i);
- }
-
- adapter = new ArrayAdapter<String>(this, R.layout.listview_item, R.id.list_item, dataSourceList);
- slideCutListView.setAdapter(adapter);
-
- slideCutListView.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- Toast.makeText(MainActivity.this, dataSourceList.get(position), Toast.LENGTH_SHORT).show();
- }
- });
- }
-
-
- //滑动删除之后的回调方法
- @Override
- public void removeItem(RemoveDirection direction, int position) {
- adapter.remove(adapter.getItem(position));
- switch (direction) {
- case RIGHT:
- Toast.makeText(this, "向右删除 "+ position, Toast.LENGTH_SHORT).show();
- break;
- case LEFT:
- Toast.makeText(this, "向左删除 "+ position, Toast.LENGTH_SHORT).show();
- break;
-
- default:
- break;
- }
-
- }
-
-
- }
这里面需要对SlideCutListView设置RemoveListener,然后我们在回调方法removeItem(RemoveDirection direction, int position)中删除该position的数据,在调用notifyDataSetChanged()刷新ListView,我这里用的是ArrayAdatper,直接调用remove()就可以了。
所有的代码就编写完了,我们来运行下程序看看效果吧
好了,今天的讲解就到此结束了,有疑问的朋友可以在下面留言,我会帮大家解答的。今天是2013年的最后一天,希望大家开开心心度过2013,也开开心心的迎接2014,提前祝大家元旦快乐!
项目源码,点击下载