1. onTouchListener(); //捕捉touch事件,比如說onDown
需要將可滑動的控件加上兩個方法:(1)view.setOnTouchListener(); //實現可以touch
(2) view.setLongClickAble(); //如果不加這個方法,這個view只會接受onDown()點擊事件。onFling() onScroll()等方法不接受
此方法需要注意,其目的是接收控件的touch事件,哪需要就要在哪加上。比如說最外面的Layout,中間的ListView,尤其注意當有ScrollView時一定要給它也加上這個方法,否則ScrollView里面的控件會不接受onFling()方法。
2. GestureDetector //手勢識別
其中我們要使用的是繼承了GestureDetector.onDoubleTapLisener和GestureDetector.OnGestureListener的GestureDetector.SimpleOnGestureListener。其中重寫onFling()方法。此方法是在快速滑動屏幕時才會執行,正好符合我們的功能。
中間我們要把自定義的GestureDetector類與控件的onTouch()方法關聯起來。在Activity中實現View.OnTouchListener(),重寫它的方法:
GestureDetector detector = new GestureDetector(new MySimpleGestureDetector());
public void onTouch(View view, MontionEvent event){
return detector.onTouchEvent(event); //關聯
}
方法體如下:附注釋
public class MySimpleGestureDetector extends GestureDetector.SimpleOnGestureListener {
    private static final int MIN_DISTANCE = 100;        //最小距離
    private static final int MIN_VELOCITY = 100;        //最小滑動速率
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (Math.abs(velocityX) > MIN_VELOCITY) {
            if ((e2.getX() - e1.getX()) > MIN_DISTANCE) {  //向右滑動
                TabActivity.flingRight();
            } else if ((e1.getX() - e2.getX()) > MIN_DISTANCE) {  //向左滑動
                TabActivity.flingLeft();
            }
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }
}
3. 此時所有支持滑動的控件都加上了touch監聽事件,並關聯到自定義的SimpleGestureDetector里。並且在自定義的SimpleGestureDetector中重寫的onFling()方法,處理了左右快速滑動操作。滑動最小距離為100px,X軸上滑動最小速率為100px/s。所以最后一步就是在你的TabActivity中處理左右滑動就可以了。附代碼:
public static void flingLeft() {
        int currentTab = tabHost.getCurrentTab();
        if (currentTab != 0) {
            currentTab--;
            switchTab(currentTab);
        }
    }
    public static void flingRight() {
        int currentTab = tabHost.getCurrentTab();
        if (currentTab != tabHost.getTabWidget().getChildCount()) {
            currentTab++;
            switchTab(currentTab);
        }
    }
    private static void switchTab(final int toTab) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                tabHost.post(new Runnable() {
                    @Override
                    public void run() {
                        tabHost.setCurrentTab(toTab);
                    }
                });
            }
        }).start();
    }
這樣一個支持左右滑動切換界面的Tab就做好了。
