Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 手勢識別實戰:ViewFlipper 搭配 GestureDetector 做滑動切換

ViewFlipper 是個很被低估的容器:它一次只顯示一個子 View,並自帶進出場動畫接口。再配上 GestureDetector 做手勢判定,幾十行代碼就能做出類似相冊左右滑動的效果。

一、布局:五張圖排隊待命

在 layout 下建立 viewflipper.xml:

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

    <ViewFlipper
        android:id="@+id/viewFlipper1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/b" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/c" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/d" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/f" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/g" />

    </ViewFlipper>

</LinearLayout>

二、Activity:手勢判定與四個動畫

核心要點有三個:讓 Activity 同時實現 OnTouchListener 與 GestureDetector.OnGestureListener;在 onTouch 裡把事件原封不動交給 GestureDetector(自己算手勢非常痛苦);調用 setLongClickable(true),否則拖動類手勢根本不會被識別。

public class ViewFlipperActivity extends Activity
        implements OnTouchListener, android.view.GestureDetector.OnGestureListener {

    private ViewFlipper flipper;
    GestureDetector mGestureDetector;
    private int mCurrentLayoutState;
    private static final int FLING_MIN_DISTANCE = 80;
    private static final int FLING_MIN_VELOCITY = 150;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewflipper);

        flipper = (ViewFlipper) this.findViewById(R.id.viewFlipper1);
        // 注冊一個用於手勢識別的類
        mGestureDetector = new GestureDetector(this);
        // 給 flipper 設置 listener
        flipper.setOnTouchListener(this);
        mCurrentLayoutState = 0;
        // 允許長按,這樣才能識別拖動等手勢
        flipper.setLongClickable(true);
    }

    /**
     * 跳轉到指定頁面(本例未直接調用,留作擴展)
     */
    public void switchLayoutStateTo(int switchTo) {
        while (mCurrentLayoutState != switchTo) {
            if (mCurrentLayoutState > switchTo) {
                mCurrentLayoutState--;
                flipper.setInAnimation(inFromLeftAnimation());
                flipper.setOutAnimation(outToRightAnimation());
                flipper.showPrevious();
            } else {
                mCurrentLayoutState++;
                flipper.setInAnimation(inFromRightAnimation());
                flipper.setOutAnimation(outToLeftAnimation());
                flipper.showNext();
            }
        }
    }

    /** 從右側進入 */
    protected Animation inFromRightAnimation() {
        Animation inFromRight = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, +1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        inFromRight.setDuration(200);
        inFromRight.setInterpolator(new AccelerateInterpolator());
        return inFromRight;
    }

    /** 向左側退出 */
    protected Animation outToLeftAnimation() {
        Animation outtoLeft = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, -1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        outtoLeft.setDuration(200);
        outtoLeft.setInterpolator(new AccelerateInterpolator());
        return outtoLeft;
    }

    /** 從左側進入 */
    protected Animation inFromLeftAnimation() {
        Animation inFromLeft = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, -1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        inFromLeft.setDuration(200);
        inFromLeft.setInterpolator(new AccelerateInterpolator());
        return inFromLeft;
    }

    /** 向右側退出 */
    protected Animation outToRightAnimation() {
        Animation outtoRight = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, +1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        outtoRight.setDuration(200);
        outtoRight.setInterpolator(new AccelerateInterpolator());
        return outtoRight;
    }

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

    /*
     * 用戶按下觸摸屏、快速移動後松開即觸發 onFling
     * e1:第一個 ACTION_DOWN MotionEvent
     * e2:最後一個 ACTION_MOVE MotionEvent
     * velocityX / velocityY:X、Y 軸移動速度,像素/秒
     * 觸發條件:位移大於 FLING_MIN_DISTANCE 且速度大於 FLING_MIN_VELOCITY
     */
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // 向左滑動
            flipper.setInAnimation(inFromRightAnimation());
            flipper.setOutAnimation(outToLeftAnimation());
            flipper.showNext();
        } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // 向右滑動
            flipper.setInAnimation(inFromLeftAnimation());
            flipper.setOutAnimation(outToRightAnimation());
            flipper.showPrevious();
        }
        return false;
    }

    public void onLongPress(MotionEvent e) { }

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

    public void onShowPress(MotionEvent e) { }

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

    public boolean onTouch(View v, MotionEvent event) {
        // 一定要把觸屏事件交給手勢識別類處理
        return mGestureDetector.onTouchEvent(event);
    }
}

三、幾個實作細節

位移與速度雙閾值是防誤觸的關鍵:只比位移,用戶慢慢拖也會翻頁;只比速度,快速抖一下又太敏感。兩個條件同時成立,手感才對。RELATIVE_TO_PARENT 配合 ±1.0f 表示「整整一屏」的位移,改成 0.5f 就是半屏,可依設計調整。四個動畫的 200 毫秒是個不容易察覺拖沓、又不會顯得突兀的區間。

由於是手勢效果,靜態截圖很難體現,建議直接跑起來用手指左右滑幾下感受。若還想要輪播,給 ViewFlipper 加上 setAutoStart(true) 與 setFlipInterval() 即可。

Copyright © Linux教程網 All Rights Reserved