Android的左滑關閉視窗

weixin_34054866發表於2017-07-19

前言

目前市場很多的APP都帶有視窗滑動切換關閉,這種切換,使得使用者操作比較爽,而且覺得功能點上也比較大氣,在此就是自己總結了一個簡易的方法,直接替換在基礎視窗裡面,使用安卓最基礎的方法進行實現;

需求說明

  1. 首先是明確從哪裡滑動:一般習慣都是從左邊緣開始滑動
  2. 手指在滑動的時候頁面進行移動
  3. 鬆開手指之後,要判斷是否滑出關閉,還是恢復以前狀態;

實現的程式碼

一、繼承一個幀佈局,重寫方法:

public class ArActSlidLayout extends FrameLayout {
// 頁面邊緣陰影的寬度預設值
private static final int SHADOW_WIDTH = 16;
private Activity mActivity;
private Scroller mScroller; //安卓自帶的一個滑動計算的類,只做計算,不參與邏輯;
// 頁面邊緣的陰影圖
private Drawable mLeftShadow; 
// 頁面邊緣陰影的寬度
private int mShadowWidth;

private int mInterceptDownX;  //手指按下,攔截的x值
private int mLastInterceptX;//記錄最後一次座標
private int mLastInterceptY;

private int mTouchDownX; //消費的x值
private int mLastTouchX;
private int mLastTouchY;

private boolean isConsumed = false;是否可以滑動

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

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

public ArActSlidLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initView(context);
}

private void initView(Context context) {
    mScroller = new Scroller(context);
    mLeftShadow = getResources().getDrawable(R.drawable.left_shadow);//得到陰影的圖形
    int density = (int) getResources().getDisplayMetrics().density;
    mShadowWidth = SHADOW_WIDTH * density;//得到實際畫素的寬度;
}

/**
 * 繫結Activity
 */
public void bindActivity(Activity activity) {
    mActivity = activity;
    ViewGroup decorView = (ViewGroup) mActivity.getWindow().getDecorView();
    View child = decorView.getChildAt(0);
    decorView.removeView(child);
    addView(child);
    decorView.addView(this);//把整個佈局新增的視窗的ViewGroup中;
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {//進行事件的是否攔截
    boolean intercept = false;
    int x = (int) ev.getX();
    int y = (int) ev.getY();
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            intercept = false;
            mInterceptDownX = x;
            mLastInterceptX = x;
            mLastInterceptY = y;
            break;
        case MotionEvent.ACTION_MOVE:
            int deltaX = x - mLastInterceptX;
            int deltaY = y - mLastInterceptY;
            // 手指處於螢幕邊緣,且橫向滑動距離大於縱向滑動距離時,攔截事件
            if (mInterceptDownX < (getWidth() / 10) && Math.abs(deltaX) > Math.abs(deltaY)) {
                intercept = true;//滿足這個條件進行攔截;
            } else {
                intercept = false;
            }
            mLastInterceptX = x;
            mLastInterceptY = y;
            break;
        case MotionEvent.ACTION_UP:
            intercept = false;
            mInterceptDownX = mLastInterceptX = mLastInterceptY = 0;//恢復資料;
            break;
    }
    //Log.e("event", " Intercep  " + "  x:  " + x + "  y:  " + y);
    return intercept;
}

@Override
public boolean onTouchEvent(MotionEvent ev) {//事件的消費,具體邏輯的編寫;
    int x = (int) ev.getX();
    int y = (int) ev.getY();
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mTouchDownX = x;
            mLastTouchX = x;
            mLastTouchY = y;
            //Log.e("event", " onTouchEventDOWN  " + "  x:  " + x + "  y:  " + y);
            break;
        case MotionEvent.ACTION_MOVE:
            int deltaX = x - mLastTouchX;
            int deltaY = y - mLastTouchY;

            if (!isConsumed && mTouchDownX < (getWidth() / 10) && Math.abs(deltaX) > Math.abs(deltaY)) {
                isConsumed = true; //移動的條件
            }

            if (isConsumed) {
                int rightMovedX = mLastTouchX - (int) ev.getX();
                // 左側即將滑出螢幕
                if (getScrollX() + rightMovedX >= 0) {
                     //移動到某一點
                    scrollTo(0, 0);
                } else {
                    //相當於累加的移動
                    scrollBy(rightMovedX, 0); //手指滑動移動整個螢幕;負數:代表向右移動 ,反之,像做
                }
               // Log.e("event", " onTouchEventMOVE  " + "  x:  " + x + "  y:  " + y + " ScrollX:  " + getScrollX() + " rightMovedX: " + rightMovedX);
            }
            mLastTouchX = x;
            mLastTouchY = y;
            break;
        case MotionEvent.ACTION_UP:
            isConsumed = false;
            mTouchDownX = mLastTouchX = mLastTouchY = 0; //消除資料;
            // 根據手指釋放時的位置決定回彈還是關閉
            if (-getScrollX() < getWidth() / 3) {
                scrollBack();
            } else {
                scrollClose();
            }
            //Log.e("event", " onTouchEventUP  " + "  x:  " + x + "  y:  " + y + " ScrollX:  " + getScrollX());
            break;
    }
    //Log.e("event"," onTouchEventAll  " + "  getRawX():  "+ev.getRawX() +"  y:  " +ev.getRawY());
    return true;
}

/**
 * 滑動返回
 */
private void scrollBack() {
    int startX = getScrollX();
    int dx = -getScrollX();
    mScroller.startScroll(startX, 0, dx, 0, 300);
    invalidate();
}

/**
 * 滑動關閉
 */
private void scrollClose() {
    int startX = getScrollX();
    int dx = -getScrollX() - getWidth();
    //Log.e("event", "  scrollClose:  dx " + dx + "  getWidth " + getWidth());
    mScroller.startScroll(startX, 0, dx, 0, 300);
    invalidate();
}

@Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        scrollTo(mScroller.getCurrX(), 0);
        //Log.e("event", "  computeScroll:  " + mScroller.getCurrX());
        postInvalidate();
    } else if (-getScrollX() >= getWidth()) {
        mActivity.finish();
        //Log.e("event", "  computeScroll: finish   " + getScrollX());
    }
}

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    drawShadow(canvas);
}

/**
 * 繪製邊緣的陰影
 */
private void drawShadow(Canvas canvas) {
    mLeftShadow.setBounds(0, 0, mShadowWidth, getHeight());
    canvas.save();
    canvas.translate(-mShadowWidth, 0);
    mLeftShadow.draw(canvas);
    canvas.restore();
 }
}

二、邊緣的陰影left_shadow.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--顏色漸變範圍-->
<gradient
    android:endColor="#50000000"
    android:startColor="#00000000" />
</shape>

三、在baseActivity裡面新增程式碼:

public class ArBaseFragActivity extends BaseMMCFragmentActivity {
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    if (setEnableSliding()) {
        ArActSlidLayout rootView = new ArActSlidLayout(this);
        rootView.bindActivity(this);//繫結需要視窗的佈局:
     }
  }

 protected boolean setEnableSliding() {//預設返回是需要的,只需繼承的時候重寫次程式碼 true : 需要;false :不需要;
    return true;
  }
}

四、總結:這種實現還有不少的方法,我這裡只是推薦了自己覺得不錯的方法,有需要的童鞋們直接copy專案中去用就行了,裡面涉及到很多安卓自帶的方法,還需要你們自己消化理解,我在實現程式碼中也進行了註釋,可以幫助你們理解消化,有什麼不足的地方,還請你們多多指教,使得我後期改進更多。

相關文章