Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Swipe Dismiss
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
// Swipe Image must be a child of parent
View swipeImage = findViewById(;
// Swipe parent should be a view that fills the screen giving swipeImage room to animate
View swipeParent = findViewById(;
swipeParent.setOnTouchListener(new SwipeImageTouchListener(swipeImage));
public static class SwipeImageTouchListener implements View.OnTouchListener{
private final View swipeView;
public SwipeImageTouchListener(View swipeView) {
this.swipeView = swipeView;
// Allows us to know if we should use MotionEvent.ACTION_MOVE
private boolean tracking = false;
// The Position where our touch event started
private float startY;
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Rect hitRect = new Rect();
if (hitRect.contains((int) event.getX(), (int) event.getY())) {
tracking = true;
startY = event.getY();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
tracking = false;
return true;
case MotionEvent.ACTION_MOVE:
if (tracking) {
swipeView.setTranslationY(event.getY() - startY);
return true;
return false;
* Using the current translation of swipeView decide if it has moved
* to the point where we want to remove it.
private void animateSwipeView(int parentHeight) {
int quarterHeight = parentHeight / 4;
float currentPosition = swipeView.getTranslationY();
float animateTo = 0.0f;
if (currentPosition < -quarterHeight) {
animateTo = -parentHeight;
} else if (currentPosition > quarterHeight) {
animateTo = parentHeight;
ObjectAnimator.ofFloat(swipeView, "translationY", currentPosition, animateTo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment