Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement feature like iOS app closing vertical Swipe-to-Dismiss with ViewPager

I currently have Views lined up horizontally in a ViewPager and can cycle through them with a PagerAdapter. Currently, to perform the action that I would like to do on swipe, I have to do a double-tap on the View's page. I could post code, but it's somewhat difficult to extract the necessary pieces...

What I would like is the ability to swipe vertically on these views, have them translate vertically with swipe and fade-out, and then perform an action when they reach a certain distance away from the edge of the device.

To get an idea of what I am thinking, in the Gallery app you can pinch an opened photo to zoom-out and open a horizontal filmstrip view. From there you can swipe up (or down) on a photo/video to delete it. For those who do not have the same Gallery app, it's exactly like closing applications on iOS.

I've tried scanning though the source code for the Gallery app, but no luck finding the correct Activity.

like image 456
OneCricketeer Avatar asked Oct 15 '15 21:10

OneCricketeer


1 Answers

view.setOnTouchListener(new View.OnTouchListener(){
    public boolean onTouch(View v, MotionEvent motion) {
       float y = motion.getY();
       /* NOTE: the following line might need to be in runOnUiThread() */
       view.animate().alpha(1-Math.abs(y-height/2)/(height/2)).setDuration(50).start();
       return true; //false if you want to pass this event on to other listeners
    }
});

The explanation for using 1-Math.abs(y-height/2)/(height/2) is that I want alpha to be 1 when I am in the center, and alpha to be 0 when it is at the top or bottom. You have to determine yourself how you obtain the height value, or if you want to use a different method to calculate alpha. If you want to get the touch position relative to the screen instead of the position relative to the view, use getRawY().

Additionally, it may be useful for you to know that to see if the MotionEvent is a press, drag, or release event, use motion.getAction() == with MotionEvent.ACTION_UP, MotionEvent.ACTION_MOVE, and MotionEvent.ACTION_DOWN, respectively.

like image 197
geokavel Avatar answered Nov 03 '22 01:11

geokavel