天天看点

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

http://blog.csdn.net/xiaanming/article/details/17539199

先说下实现该效果的主要思路

先根据手指触摸的点来获取点击的是listview的哪一个item

手指在屏幕中滑动我们利用scrollby()来使该item跟随手指一起滑动

手指放开的时候,我们判断手指拖动的距离来判断item到底是滑出屏幕还是回到开始位置

主要思路就是上面这三步,接下来我们就用代码来实现吧,首先我们新建一个项目,叫slidecutlistview

根据需求我们需要自己自定义一个listview来实现该功能,接下来先贴出代码再讲解具体的实现

[java] view

plaincopy

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果
Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

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;  

/** 

 * @blog http://blog.csdn.net/xiaanming 

 *  

 * @author xiaanming 

 */  

public class slidecutlistview extends listview {  

    /** 

     * 当前滑动的listview position 

     */  

    private int slideposition;  

     * 手指按下x的坐标 

    private int downy;  

     * 手指按下y的坐标 

    private int downx;  

     * 屏幕宽度 

    private int screenwidth;  

     * listview的item 

    private view itemview;  

     * 滑动类 

    private scroller scroller;  

    private static final int snap_velocity = 600;  

     * 速度追踪对象 

    private velocitytracker velocitytracker;  

     * 是否响应滑动,默认为不响应 

    private boolean isslide = false;  

     * 认为是用户滑动的最小距离 

    private int mtouchslop;  

     *  移除item后的回调接口 

    private removelistener mremovelistener;  

     * 用来指示item滑出屏幕的方向,向左或者向右,用一个枚举值来标记 

    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();  

     * 设置滑动删除的回调接口 

     * @param removelistener 

    public void setremovelistener(removelistener removelistener) {  

        this.mremovelistener = removelistener;  

     * 分发事件,主要做的是判断点击的是那个item, 以及通过postdelayed来设置响应左右滑动事件 

    @override  

    public boolean dispatchtouchevent(motionevent event) {  

        switch (event.getaction()) {  

        case motionevent.action_down: {  

            addvelocitytracker(event);  

            // 假如scroller滚动还没有结束,我们直接返回  

            if (!scroller.isfinished()) {  

                return super.dispatchtouchevent(event);  

            }  

            downx = (int) event.getx();  

            downy = (int) event.gety();  

            slideposition = pointtoposition(downx, downy);  

            // 无效的position, 不做任何处理  

            if (slideposition == adapterview.invalid_position) {  

            // 获取我们点击的item view  

            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;  

        case motionevent.action_up:  

            recyclevelocitytracker();  

        return super.dispatchtouchevent(event);  

     * 往右滑动,getscrollx()返回的是左边缘的距离,就是以view左边缘为原点到开始滑动的距离,所以向右边滑动为负值 

    private void scrollright() {  

        removedirection = removedirection.right;  

        final int delta = (screenwidth + itemview.getscrollx());  

        // 调用startscroll方法来设置一些滚动的参数,我们在computescroll()方法中调用scrollto来滚动item  

        scroller.startscroll(itemview.getscrollx(), 0, -delta, 0,  

                math.abs(delta));  

        postinvalidate(); // 刷新itemview  

     * 向左滑动,根据上面我们知道向左滑动为正值 

    private void scrollleft() {  

        removedirection = removedirection.left;  

        final int delta = (screenwidth - itemview.getscrollx());  

        scroller.startscroll(itemview.getscrollx(), 0, delta, 0,  

     * 根据手指滚动itemview的距离来判断是滚动到开始位置还是向左或者向右滚动 

    private void scrollbydistancex() {  

        // 如果向左滚动的距离大于屏幕的三分之一,就让其删除  

        if (itemview.getscrollx() >= screenwidth / 3) {  

            scrollleft();  

        } else if (itemview.getscrollx() <= -screenwidth / 3) {  

            scrollright();  

        } else {  

            // 滚回到原始位置,为了偷下懒这里是直接调用scrollto滚动  

            itemview.scrollto(0, 0);  

     * 处理我们拖动listview item的逻辑 

    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滚动, deltax大于0向左滚动,小于0向右滚  

                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;  

            return true; // 拖动的时候listview不滚动  

        //否则直接交给listview来处理ontouchevent事件  

        return super.ontouchevent(ev);  

    public void computescroll() {  

        // 调用startscroll的时候scroller.computescrolloffset()返回true,  

        if (scroller.computescrolloffset()) {  

            // 让listview item根据当前的滚动偏移量进行滚动  

            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);  

     * 添加用户的速度跟踪器 

     *  

     * @param event 

    private void addvelocitytracker(motionevent event) {  

        if (velocitytracker == null) {  

            velocitytracker = velocitytracker.obtain();  

        velocitytracker.addmovement(event);  

     * 移除用户速度跟踪器 

    private void recyclevelocitytracker() {  

        if (velocitytracker != null) {  

            velocitytracker.recycle();  

            velocitytracker = null;  

     * 获取x方向的滑动速度,大于0向右滑动,反之向左 

     * @return 

    private int getscrollvelocity() {  

        velocitytracker.computecurrentvelocity(1000);  

        int velocity = (int) velocitytracker.getxvelocity();  

        return velocity;  

     * 当listview item滑出屏幕,回调这个接口 

     * 我们需要在回调方法removeitem()中移除该item,然后刷新listview 

     * @author xiaanming 

     * 

    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()里面的这段代码

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果
Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

itemview.scrollto(0, 0);  

我们需要将该item滚动在(0, 0 )这个点,因为我们只是将listview的item滚动出屏幕而已,并没有将该item移除,而且我们不能手动调用removeview()来从listview中移除该item,我们只能通过改变listview的数据,然后通过notifydatasetchanged()来刷新listview,所以我们需要将其滚动至(0, 0),这里比较关键。

定义好了我们左右滑动的listview,接下来就来使用它,布局很简单,一个relativelayout包裹我们自定义的listview

[html] view

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果
Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

<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的布局

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果
Android 使用Scroller实现绚丽的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,相信大家都能看懂

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果
Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

import java.util.arraylist;  

import java.util.list;  

import android.app.activity;  

import android.os.bundle;  

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>();  

    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();  

        });  

    //滑动删除之后的回调方法  

    public void removeitem(removedirection direction, int position) {  

        adapter.remove(adapter.getitem(position));  

        switch (direction) {  

        case right:  

            toast.maketext(this, "向右删除  "+ position, toast.length_short).show();  

        case left:  

            toast.maketext(this, "向左删除  "+ position, toast.length_short).show();  

        default:  

    }     

这里面需要对slidecutlistview设置removelistener,然后我们在回调方法removeitem(removedirection direction, int position)中删除该position的数据,在调用notifydatasetchanged()刷新listview,我这里用的是arrayadatper,直接调用remove()就可以了。

所有的代码就编写完了,我们来运行下程序看看效果吧

Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果

好了,今天的讲解就到此结束了,有疑问的朋友可以在下面留言,我会帮大家解答的。今天是2013年的最后一天,希望大家开开心心度过2013,也开开心心的迎接2014,提前祝大家元旦快乐!

项目源码,点击下载

继续阅读