I am trying to make an app where a user can swipe and change which fragment they are seeing on the screen. I can not use view pager because I want the user to be able to swipe to different fragments forever. Here is the detector in my fragment:
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE & Math.abs(velocityX) > 10) {
left();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE & Math.abs(velocityX) > 10) {
right();
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE & distanceX > distanceY) {
left();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE & distanceX > distanceY) {
right();
}
return false;
}
}
public void right(){
mCallback.dateNumber(true);
sportView.setText("Loading");
}public void left(){
mCallback.dateNumber(false);
sportView.setText("Loading");
}
In my activity, here is the listener that I added to change fragments:
@Override
public void dateNumber(Boolean left_right) {
//true == right
//false == left
if(left_right == false){
day = day + 1;
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();
}else if(left_right == true){
day = day - 1;
Fragment1 leftFragment = new Fragment1();
Bundle args = new Bundle();
args.putInt("day", day);
leftFragment.setArguments(args);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, leftFragment);
transaction.addToBackStack(null);
transaction.commit();
}
left_right = null;
}
I know that the swipe gesture is always being recognized but sometimes the new fragment won't open up. Does anyone know why?