简体   繁体   中英

How to implement swipe (left/right) gesture in a layout in Android Studio?

My intention is to implement swipe in a layout. On swiping from left or right in the layout, one view will be visible and hidden.

Am using Android Studio. Is there any library available which can be used directly?

You can use onfling gesture listener. Sample code for you given below

public class MyActivity extends Activity {
private void onCreate() {
 // Set your layout
 final ImageView imageView = (ImageView) findViewById(R.id.image_view);
 imageView.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(final View view, final MotionEvent event) {
       return gdt.onTouchEvent(event);
    }
 });
  }

  private final GestureDetector gdt = new GestureDetector(new     GestureListener());

  private class GestureListener extends SimpleOnGestureListener {

 private final int SWIPE_MIN_DISTANCE = 120;
 private final int SWIPE_THRESHOLD_VELOCITY = 200;

 @Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) >     SWIPE_THRESHOLD_VELOCITY) {
       // Right to left, your code here
       return true;
    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE &&     Math.abs(velocityX) >  SWIPE_THRESHOLD_VELOCITY) {
       // Left to right, your code here
       return true;
    }
    if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) >     SWIPE_THRESHOLD_VELOCITY) {
       // Bottom to top, your code here
       return true;
    } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE &&    Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
       // Top to bottom, your code here
       return true;
    }
    return false;
   }
  }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM