您的位置:首页 > 移动开发 > Android开发

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

2013-07-25 11:07 309 查看
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就做好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: