码迷,mamicode.com
首页 > 移动开发 > 详细

android开发步步为营之72:右滑关闭Activity

时间:2015-08-31 23:51:36      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:右滑关闭activity

           通过右滑手势关闭当前Activity,这个是很常见的需求,网上参考过几篇文章发现实现都比较复杂,他们大多自己另外写了个Layout,然后这个Layout当做页面的布局,经测试其实有更简单一点的方法,写个BaseActivity,其他Activity继承即可。这里给出代码,大家测试看看。有问题回馈一下,谢谢!

          

package com.figo.study.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class BaseActivity extends Activity implements View.OnTouchListener, GestureDetector.OnGestureListener {
    GestureDetector mGestureDetector;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGestureDetector = new GestureDetector((GestureDetector.OnGestureListener) this);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    private int verticalMinDistance = 20;
    private int minVelocity = 0;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (Math.abs(e2.getY() - e1.getY()) > 200) {//这里是避免有scroolview的页面上划也关闭
            return false;
        }
        if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {//左滑操作
        } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {//右滑操作
            this.finish();
        }

        return false;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

android开发步步为营之72:右滑关闭Activity

标签:右滑关闭activity

原文地址:http://blog.csdn.net/figo0423/article/details/48140409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!