package com.veryedu.tabhost;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
public class MainActivity extends TabActivity implements OnGestureListener {
GestureDetector gestureDetector;
static TabHost tabHost;
static int index = 0;
int count;
static Bundle bundle=new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = getTabHost();
// 添加选项卡的标题和内容
TabSpec spec1 = tabHost.newTabSpec("lab1");
spec1.setIndicator("选项卡一");
spec1.setContent(new Intent(this, Tab1Activity.class));
tabHost.addTab(spec1);
TabSpec spec2 = tabHost.newTabSpec("lab2");
spec2.setIndicator("选项卡二");
spec2.setContent(new Intent(this, Tab2Activity.class));
tabHost.addTab(spec2);
TabSpec spec3 = tabHost.newTabSpec("lab3");
spec3.setIndicator("选项卡三");
spec3.setContent(new Intent(this, Tab3Activity.class));
tabHost.addTab(spec3);
TabSpec spec4 = tabHost.newTabSpec("lab4");
spec4.setIndicator("选项卡四");
spec4.setContent(new Intent(this, Tab4Activity.class));
tabHost.addTab(spec4);
TabSpec spec5 = tabHost.newTabSpec("lab5");
spec5.setIndicator("选项卡五");
spec5.setContent(new Intent(this, Tab5Activity.class));
tabHost.addTab(spec5);
TabSpec spec6 = tabHost.newTabSpec("lab6");
spec6.setIndicator("选项卡六");
spec6.setContent(new Intent(this, Tab6Activity.class));
tabHost.addTab(spec6);
//获取控件数量
TabWidget tabWidget=(TabWidget)findViewById(android.R.id.tabs);
count=tabWidget.getChildCount();
gestureDetector=new GestureDetector(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if(e1.getX()>e2.getX()){
//向左滑动,选项卡前进到下一个
if(index<count){
tabHost.setCurrentTab(++index);
}
}else if(e1.getX()<e2.getX()){
//向右滑动,选项卡后退到前一个
if(index>0){
tabHost.setCurrentTab(--index);
}
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
将变量申明为static静态即可