I know there are plenty of questions regarding this topic. I've had a look at most of them, but still I'm not able to debug my code. It does not detect swipes. I'm a beginner to both Android programming as well as Java, so please don't be too critical.
- I have a simple Linear Layout, with a Button that fills the whole layout. Everytime the button is clicked, it's value increments by 1.
- I'm trying to implement left on right swipes. My basic doubt is should I implement the setOnTouchListener with the Button or the Linear Layout?
I've seen people use OnGestureListener and OnTouchListener. Which one is preferable?
public class MainActivity extends Activity implements OnClickListener{ public Button increment; public int cnt= 0; private static final int SWIPE_MIN_DISTANCE = 80; private static final int SWIPE_THRESHOLD_VELOCITY = 40; GestureDetector gestureDetector; LinearLayout swipe_layout= (LinearLayout)findViewById(R.id.linear); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); increment= (Button)findViewById(R.id.numberkey); increment.setOnClickListener(this); setDisplay(0); gestureDetector= new GestureDetector(this, new Detector()); increment.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); return true; } }); } @Override public void onClick(View v) { setDisplay(cnt++); } private void setDisplay(int i) { increment.setText(String.valueOf(i)); } class Detector extends SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); } return false; } }
}
Thanks in advance.