我需要在滑动时更改 FragmentTabHost 中的选项卡。TabHost 中的每个选项卡实际上都显示了另一个片段。我使用了此处显示的一些代码:Android Fragment onCreateView with Gestures,但它似乎不适用于我的场景。
public class OpenedGlimpsedMenuDrawer extends Fragment {
private FragmentTabHost mTabHost;
//Mandatory Constructor
public OpenedGlimpsedMenuDrawer() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabs_fragment_menudrawer,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Opened").setIndicator("Opened"),
OpenedFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Glimpsed").setIndicator("Glimpsed"),
GlimpsedFragment.class, null);
final GestureDetector gesture = new GestureDetector(getActivity(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
Log.i("FLING IS CALLED!!", "OnDown Method");
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final int SWIPE_MIN_DISTANCE = 120;
final int SWIPE_MAX_OFF_PATH = 250;
final int SWIPE_THRESHOLD_VELOCITY = 200;
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Log.i("FLING IS CALLED!!", "Right to Left");
mTabHost.setCurrentTab(1);
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
mTabHost.setCurrentTab(0);
Log.i("FLING IS CALLED!!", "Left to Right");
}
} catch (Exception e) {
// nothing
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});
rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gesture.onTouchEvent(event);
}
});
return rootView;
}
}