Android swipe layout to dismiss
Asked Answered
H

3

7

I'm trying to make a swipeable layout so you can swipe it to dismiss like in Google now. I managed to getting it worked on a view such as button using this codes:

SwipeDismissTouchListener:

public class SwipeDismissTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;

// Fixed properties
private View mView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

// Transient properties
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private Object mToken;
private VelocityTracker mVelocityTracker;
private float mTranslationX;

/**
 * The callback interface used by {@link SwipeDismissTouchListener} to inform its client
 * about a successful dismissal of the view for which it was created.
 */
public interface DismissCallbacks {
    /**
     * Called to determine whether the view can be dismissed.
     */
    boolean canDismiss(Object token);

    /**
     * Called when the user has indicated they she would like to dismiss the view.
     *
     * @param view  The originating {@link android.view.View} to be dismissed.
     * @param token The optional token passed to this object's constructor.
     */
    void onDismiss(View view, Object token);
}

/**
 * Constructs a new swipe-to-dismiss touch listener for the given view.
 *
 * @param view     The view to make dismissable.
 * @param token    An optional token/cookie object to be passed through to the callback.
 * @param callbacks The callback to trigger when the user has indicated that she would like to
 *                 dismiss this view.
 */
public SwipeDismissTouchListener(View view, Object token, DismissCallbacks callbacks) {
    ViewConfiguration vc = ViewConfiguration.get(view.getContext());
    mSlop = vc.getScaledTouchSlop();
    mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
    mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
    mAnimationTime = view.getContext().getResources().getInteger(
            android.R.integer.config_shortAnimTime);
    mView = view;
    mToken = token;
    mCallbacks = callbacks;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    // offset because the view is translated during swipe
    motionEvent.offsetLocation(mTranslationX, 0);

    if (mViewWidth < 2) {
        mViewWidth = mView.getWidth();
    }

    switch (motionEvent.getActionMasked()) {
        case MotionEvent.ACTION_DOWN: {
            // TODO: ensure this is a finger, and set a flag
            mDownX = motionEvent.getRawX();
            mDownY = motionEvent.getRawY();
            if (mCallbacks.canDismiss(mToken)) {
                mVelocityTracker = VelocityTracker.obtain();
                mVelocityTracker.addMovement(motionEvent);
            }
            return false;
        }

        case MotionEvent.ACTION_UP: {
            if (mVelocityTracker == null) {
                break;
            }

            float deltaX = motionEvent.getRawX() - mDownX;
            mVelocityTracker.addMovement(motionEvent);
            mVelocityTracker.computeCurrentVelocity(1000);
            float velocityX = mVelocityTracker.getXVelocity();
            float absVelocityX = Math.abs(velocityX);
            float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
            boolean dismiss = false;
            boolean dismissRight = false;
            if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
                dismiss = true;
                dismissRight = deltaX > 0;
            } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                    && absVelocityY < absVelocityX
                    && absVelocityY < absVelocityX && mSwiping) {
                // dismiss only if flinging in the same direction as dragging
                dismiss = (velocityX < 0) == (deltaX < 0);
                dismissRight = mVelocityTracker.getXVelocity() > 0;
            }
            if (dismiss) {
                // dismiss
                mView.animate()
                        .translationX(dismissRight ? mViewWidth : -mViewWidth)
                        .alpha(0)
                        .setDuration(mAnimationTime)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                performDismiss();
                            }
                        });
            } else if (mSwiping) {
                // cancel
                mView.animate()
                        .translationX(0)
                        .alpha(1)
                        .setDuration(mAnimationTime)
                        .setListener(null);
            }
            mVelocityTracker.recycle();
            mVelocityTracker = null;
            mTranslationX = 0;
            mDownX = 0;
            mDownY = 0;
            mSwiping = false;
            break;
        }

        case MotionEvent.ACTION_CANCEL: {
            if (mVelocityTracker == null) {
                break;
            }

            mView.animate()
                    .translationX(0)
                    .alpha(1)
                    .setDuration(mAnimationTime)
                    .setListener(null);
            mVelocityTracker.recycle();
            mVelocityTracker = null;
            mTranslationX = 0;
            mDownX = 0;
            mDownY = 0;
            mSwiping = false;
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            if (mVelocityTracker == null) {
                break;
            }

            mVelocityTracker.addMovement(motionEvent);
            float deltaX = motionEvent.getRawX() - mDownX;
            float deltaY = motionEvent.getRawY() - mDownY;
            if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                mSwiping = true;
                mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
                mView.getParent().requestDisallowInterceptTouchEvent(true);

                // Cancel listview's touch
                MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                        (motionEvent.getActionIndex() <<
                                MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                mView.onTouchEvent(cancelEvent);
                cancelEvent.recycle();
            }

            if (mSwiping) {
                mTranslationX = deltaX;
                mView.setTranslationX(deltaX - mSwipingSlop);
                // TODO: use an ease-out interpolator or such
                mView.setAlpha(Math.max(0f, Math.min(1f,
                        1f - 2f * Math.abs(deltaX) / mViewWidth)));
                return true;
            }
            break;
        }
    }
    return false;
}

private void performDismiss() {
    // Animate the dismissed view to zero-height and then fire the dismiss callback.
    // This triggers layout on each animation frame; in the future we may want to do something
    // smarter and more performant.

    final ViewGroup.LayoutParams lp = mView.getLayoutParams();
    final int originalHeight = mView.getHeight();

    ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

    animator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mCallbacks.onDismiss(mView, mToken);
            // Reset view presentation
            mView.setAlpha(1f);
            mView.setTranslationX(0);
            lp.height = originalHeight;
            mView.setLayoutParams(lp);
        }
    });

    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            lp.height = (Integer) valueAnimator.getAnimatedValue();
            mView.setLayoutParams(lp);
        }
    });

    animator.start();
}
}

Calling it:

    dismissableButton.setOnTouchListener(new SwipeDismissTouchListener(
            dismissableButton,
            null,
            new SwipeDismissTouchListener.DismissCallbacks() {
                @Override
                public boolean canDismiss(Object token) {
                    return true;
                }
                @Override
                public void onDismiss(View view, Object token) {
                group.removeView(dismissableButton);
             }
     }));

I want to make this code work on a layout so i could swipe the layout to dismiss, for example so i could place a RelativeLayout inside a ViewGroup and make the RelativeLayout swipeable to dismiss.

Handcuff answered 8/7, 2014 at 21:33 Comment(0)
E
11

I just used the same SwipeDismissTouchListener class to implement a swipe gesture on a RelativeLayout, and at first had the problem of ACTION_MOVE never getting passed through, or any action other than ACTION_DOWN.

Found out that the problem is in ACTION_DOWN returning false. So just change your case ACTION_DOWN to return true, and it will work properly, as that will make other actions also get passed through.

Elinoreeliot answered 20/3, 2015 at 19:26 Comment(1)
just needs the return true if canDismiss returns truePing
F
1

you should know that if you return false for action_down , you will not get any further actions regarding this touch event

https://developer.android.com/training/gestures/detector#capture-touch-events-for-an-activity-or-view

"Beware of creating a listener that returns false for the ACTION_DOWN event. If you do this, the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events. This is because ACTION_DOWN is the starting point for all touch events."

Foss answered 4/10, 2018 at 18:54 Comment(0)
P
0

This code worked for me. I was able to Swipe-dismiss Relative and Linear Layouts. Just make sure you call the removeView() method from the correct immediate parent layout.

            @Override
            public void onDismiss(View view, Object token) {
            ViewGroup parent=(ViewGroup)dissmissableLayout.getParent();
            parent.removeView(dismissableLayout);
            }
Punchdrunk answered 5/8, 2014 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.