您可以使用 droidQuery:https ://github.com/phil-brown/droidQuery 。它将真正简化您的代码并使其易于使用。以下是您需要在活动 onCreate() 中添加的所有内容:
//global variables
private boolean isSwiping = false;
private SwipeDetector.Direction swipeDirection = null;
private View v;//set to the parent layout of the fragments.
//swipe-handling code
$.with(v).swipe(new Function() {
@Override
public void invoke($ droidQuery, Object... params) {
if (params[0] == SwipeDetector.Direction.START)
isSwiping = true;
else if (params[0] == SwipeDetector.Direction.STOP) {
if (isSwiping) {
isSwiping = false;
if (swipeDirection != null) {
switch(swipeDirection) {
case DOWN :
//TODO: Down swipe complete, so do something
break;
case UP :
//TODO: Up swipe complete, so do something
break;
case LEFT :
//TODO: Left swipe complete, so do something
break;
case RIGHT :
//TODO: Right swipe complete, so do something (such as):
day++;
Fragment1 rightFragment = new Fragment1();
Bundle args = new Bundle();
args.putInt("day", day);
rightFragment.setArguments(args);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, rightFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
default :
break;
}
}
}
}
else {
swipeDirection = (SwipeDetector.Direction) params[0];
}
}
});