滑动删除

Paste_Image.png

上代码

public class SwipeLayout extends FrameLayout {
    private static final String TAG = "SwipeLayout";
    private ViewDragHelper dragHelper;
    private View content,delete;
    private boolean result;

    public SwipeLayout(Context context) {
        this(context, null);
    }

    public SwipeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        dragHelper = ViewDragHelper.create(this, callback);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        content = getChildAt(0);
        delete = getChildAt(1);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//        super.onLayout(changed, left, top, right, bottom);
        content.layout(0,0,content.getMeasuredWidth(),content.getMeasuredHeight());
        delete.layout(content.getRight(),0,content.getRight()+delete.getMeasuredWidth(),
                delete.getMeasuredHeight());
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        result = dragHelper.shouldInterceptTouchEvent(ev);
        return result;
    }

    float downX,downY;
    long downTime;//按下的时间
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //让dragHelper帮助我们处理触摸事件
        dragHelper.processTouchEvent(event);

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                downTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                float moveY = event.getY();
                //1.计算移动的距离
                float dx = moveX - downX;
                float dy = moveY - downY;
                //2.判断移动的方向
                if(Math.abs(dx) > Math.abs(dy)){
                    //说明偏向于x方向,那么我们就认为用户是想滑动条目,则请求listview不要拦截了
                    requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_UP:
                float deltaX = event.getX() - downX;
                float deltaY = event.getY() - downY;
                //计算按下抬起的距离,其实就是斜边了
                float distance = (float) Math.sqrt(Math.pow(deltaX, 2)+Math.pow(deltaY, 2));

                //计算按下抬起的时间
                long duration = System.currentTimeMillis() - downTime;

                //如果时间小于500,并且距离小于8px,则认为是点击事件
                if(duration< ViewConfiguration.getLongPressTimeout() && distance<ViewConfiguration.getTouchSlop())
                {
                    //作用让view的onClickListener进行调用
                    performClick();
                }
                break;
        }

        return true;
    }

    ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            return true;
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return 1;
        }

        /**
         * 修正View的水平滑动位置
         * @param child
         * @param left
         * @param dx
         * @return
         */
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            if(child==content){
                if(left>0){
                    left = 0;
                }else if(left<-delete.getMeasuredWidth()){
                    left = -delete.getMeasuredWidth();
                }
            }else if(child==delete){
                if(left>content.getMeasuredWidth()){
                    left = content.getMeasuredWidth();
                }else if(left<(content.getMeasuredWidth()-delete.getMeasuredWidth())){
                    left = (content.getMeasuredWidth()-delete.getMeasuredWidth());
                }
            }


            return left;
        }

        /**
         * 伴随移动
         * @param changedView
         * @param left
         * @param top
         * @param dx
         * @param dy
         */
        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);
            //如果滑动的是content,那就让delete进行移动
            if(changedView==content){
                ViewCompat.offsetLeftAndRight(delete,dx);
            }else if(changedView==delete){
                ViewCompat.offsetLeftAndRight(content,dx);
            }

            //回调接口的方法
            if(listener!=null){
                if(content.getLeft()==0){
                    listener.onClose(SwipeLayout.this);
                }else if(content.getLeft()==-delete.getMeasuredWidth()){
                    listener.onOpen(SwipeLayout.this);
                }
            }

        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            super.onViewReleased(releasedChild, xvel, yvel);
            if(content.getLeft()<-delete.getMeasuredWidth()/2){
                //open
                dragHelper.smoothSlideViewTo(content, -delete.getMeasuredWidth(), 0);
                ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
            }else {
                //close
                dragHelper.smoothSlideViewTo(content, 0, 0);
                ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
            }
        }
    };

    public void close(){
        dragHelper.smoothSlideViewTo(content, 0, 0);
        ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if(dragHelper.continueSettling(true)){
            ViewCompat.postInvalidateOnAnimation(SwipeLayout.this);
        }
    }

    private OnSwipeListener listener;
    public void setOnSwipeListener(OnSwipeListener listener){
        this.listener = listener;
    }

    public interface OnSwipeListener{
        void onOpen(SwipeLayout layout);
        void onClose(SwipeLayout layout);
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.kailing.swipedelete.SwipeLayout
        android:id="@+id/swipeLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <!--Content的布局-->
        <include layout="@layout/layout_content"/>

        <!--Delete的布局-->
        <include layout="@layout/layout_delete"/>

    </com.kailing.swipedelete.SwipeLayout>

</LinearLayout>

content

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:paddingLeft="15dp"
    android:background="#33666666"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/head_1"/>
    
    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#99000000"
        android:id="@+id/tv_name"
        android:layout_marginLeft="10dp"
        android:textSize="20sp"
        android:text="名称"/>

</LinearLayout>

delete

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:orientation="horizontal" >

    <TextView android:layout_width="100dp"
        android:layout_height="match_parent"
        android:textSize="18sp"
        android:textColor="#ffffff"
        android:gravity="center"
        android:background="#aa000000"
        android:text="Call"/>
    
    <TextView android:layout_width="100dp"
        android:layout_height="match_parent"
        android:textSize="18sp"
        android:textColor="#ffffff"
        android:id="@+id/tv_delete"
        android:gravity="center"
        android:background="#eeff0000"
        android:text="Delete"/>

</LinearLayout>

mainactivity

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @BindView(R.id.listview)
    ListView listview;

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

        listview.setAdapter(new MyAdapter());

        //监听listview滑动
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //当滑动listview的时候关闭已经打开的
                if(openedLayout!=null){
                    openedLayout.close();
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "aaaaaa", Toast.LENGTH_SHORT).show();
            }
        });
    }

    SwipeLayout openedLayout = null;//用来记录当前已经打开的SwipeLayout
    class MyAdapter extends BaseAdapter implements SwipeLayout.OnSwipeListener{

        @Override
        public int getCount() {
            return Constant.NAMES.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            MyHolder myHolder = null;
            if(convertView== null){
                convertView = View.inflate(parent.getContext(), R.layout.adapter_list, null);
                myHolder = new MyHolder(convertView);
                convertView.setTag(myHolder);
            }else {
                myHolder = (MyHolder) convertView.getTag();
            }

            //绑定数据
            myHolder.tvName.setText(Constant.NAMES[position]);
            
            myHolder.swipeLayout.setOnSwipeListener(this);

            myHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, Constant.NAMES[position], Toast.LENGTH_SHORT).show();
                }
            });

            return convertView;
        }


        @Override
        public void onOpen(SwipeLayout layout) {
            //先关闭已经打开了的
            if(openedLayout!=null && openedLayout!=layout){
                openedLayout.close();
            }

            openedLayout = layout;
        }

        @Override
        public void onClose(SwipeLayout layout) {
            //将已经打开的置为null
            if(openedLayout==layout){
                openedLayout = null;
            }
        }
    }

    static class MyHolder {
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_delete)
        TextView tvDelete;
        @BindView(R.id.swipeLayout)
        SwipeLayout swipeLayout;

        MyHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容