android開發步步為營之72:右滑關閉Activity

來源:互聯網
上載者:User

android開發步步為營之72:右滑關閉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;    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.