Created
June 18, 2015 16:03
-
-
Save anonymous/3b25e358e87334292ce5 to your computer and use it in GitHub Desktop.
Swipe Dismiss
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.animation.ObjectAnimator; | |
import android.graphics.Rect; | |
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.view.MotionEvent; | |
import android.view.View; | |
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
// Swipe Image must be a child of parent | |
View swipeImage = findViewById(R.id.swipe_image); | |
// Swipe parent should be a view that fills the screen giving swipeImage room to animate | |
View swipeParent = findViewById(R.id.swipe_parent); | |
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; | |
@Override | |
public boolean onTouch(View v, MotionEvent event) { | |
switch (event.getAction()) { | |
case MotionEvent.ACTION_DOWN: | |
Rect hitRect = new Rect(); | |
swipeView.getHitRect(hitRect); | |
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; | |
animateSwipeView(v.getHeight()); | |
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) | |
.setDuration(200) | |
.start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment