android tab之间滑动切换界面功能

1. onTouchListener();                       //捕捉touch事件,好比说onDownide

   须要将可滑动的控件加上两个方法:(1)view.setOnTouchListener();  //实现能够touchpost

                  (2)  view.setLongClickAble();  //若是不加这个方法,这个view只会接受onDown()点击事件。onFling() onScroll()等方法不接受继承

  此方法须要注意,其目的是接收控件的touch事件,哪须要就要在哪加上。好比说最外面的Layout,中间的ListView,尤为注意当有ScrollView时必定要给它也加上这个方法,不然ScrollView里面的控件会不接受onFling()方法。事件

2.  GestureDetector   //手势识别ci

     其中咱们要使用的是继承了GestureDetector.onDoubleTapLisener和GestureDetector.OnGestureListener的GestureDetector.SimpleOnGestureListener。其中重写onFling()方法。此方法是在快速滑动屏幕时才会执行,正好符合咱们的功能。get

     中间咱们要把自定义的GestureDetector类与控件的onTouch()方法关联起来。在Activity中实现View.OnTouchListener(),重写它的方法:it

     GestureDetector detector = new GestureDetector(new MySimpleGestureDetector());io

  public void onTouch(View view, MontionEvent event){event

    return detector.onTouchEvent(event);   //关联class

    }

 

方法体以下:附注释

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就作好了。

相关文章
相关标签/搜索