Question

I'm looking for a way to change the content of TextViews when the user swipes the layout holding those Views. My goal is something like that: enter image description here

I'm trying to do this with a SimpleOnGestureListener(code goes below). The problem: when I swipe from left to right, the value of i becomes -1 and no reaction occures of following swipes. Right to left swipe causes i to become 1 (where the hell is zero?) and the View stops reacting on swipes again. What am I doing wrong?

     public class MainActivity extends Activity {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
public View mainview;
public TextView lol;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gestureDetector = new GestureDetector(new MyGestureDetector());
    mainview = (View) findViewById(R.id.mainView);
    lol = (TextView) findViewById(R.id.textView2);

    mainview.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        int i = 0;

        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) {
            i++;
            lol.setText("Text" + " " + Integer.toString(i));

            return true;
        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            i--;
            lol.setText("Text" + " " + Integer.toString(i));

            return true;
        }

        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
}
    }
Was it helpful?

Solution

Why don't you use viewPager? It does exactly what you need and supports indicators. There are some custom libs with indicators where you can find exact indicator you need, e.g. this one is nice.

OTHER TIPS

Instead of managing gestures use a Gallery or Horizontal ScrollView or ViewPager

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top