Android Open Source - Xpense Swipe Dismiss List View Touch Listener






From Project

Back to project page Xpense.

License

The source code is released under:

MIT License

If you think the Android project Xpense listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.kevinzhu.xpense;
//from w  w  w  .  j ava2 s .  co m
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ListView;

import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.List;

/**
 * A {@link View.OnTouchListener} that makes the list items in a {@link ListView}
 * dismissable. {@link ListView} is given special treatment because by default it handles touches
 * for its list items... i.e. it's in charge of drawing the pressed state (the list selector),
 * handling list item clicks, etc.
 *
 * <p>After creating the listener, the caller should also call
 * {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}, passing
 * in the scroll listener returned by {@link #makeScrollListener()}. If a scroll listener is
 * already assigned, the caller should still pass scroll changes through to this listener. This will
 * ensure that this {@link SwipeDismissListViewTouchListener} is paused during list view
 * scrolling.</p>
 *
 * <p>Example usage:</p>
 *
 * <pre>
 * SwipeDismissListViewTouchListener touchListener =
 *         new SwipeDismissListViewTouchListener(
 *                 listView,
 *                 new SwipeDismissListViewTouchListener.OnDismissCallback() {
 *                     public void onDismiss(ListView listView, int[] reverseSortedPositions) {
 *                         for (int position : reverseSortedPositions) {
 *                             adapter.remove(adapter.getItem(position));
 *                         }
 *                         adapter.notifyDataSetChanged();
 *                     }
 *                 });
 * listView.setOnTouchListener(touchListener);
 * listView.setOnScrollListener(touchListener.makeScrollListener());
 * </pre>
 *
 * <p>This class Requires API level 12 or later due to use of {@link
 * ViewPropertyAnimator}.</p>
 *
 */
public class SwipeDismissListViewTouchListener 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 ListView mListView;
    private DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
    private int mDismissAnimationRefCount = 0;
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private VelocityTracker mVelocityTracker;
    //Gets the position of child in Listview, ranges from 0 to length(Listview)
    private int mDownPosition;
    private View mDownView;
    private ImageButton edit;
    private ImageButton delete;
    private boolean mPaused;

    private String mCurrentListType;

    private Context mCurrentContext;

    //The child in the listView that's currently been swiped to the right
    //Layout will be reset once a touch occurs again.
    private View focusedChild = null;

    /**
     * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client
     * about a successful dismissal of one or more list item positions.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the given position can be dismissed.
         */
        boolean canDismiss(int position);

        /**
         * Called when the user has indicated they she would like to dismiss one or more list item
         * positions.
         *
         * @param listView               The originating {@link ListView}.
         * @param reverseSortedPositions An array of positions to dismiss, sorted in descending
         *                               order for convenience.
         */
        void onDismiss(ListView listView, int[] reverseSortedPositions);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given list view.
     *
     * @param listView  The list view whose items should be dismissable.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                  dismiss one or more list items.
     */
    public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks, Context c, String currentListType) {
        ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = listView.getContext().getResources().getInteger(
                android.R.integer.config_shortAnimTime);
        mListView = listView;
        mCallbacks = callbacks;
        mCurrentContext = c;
        mCurrentListType = currentListType;
    }

    /**
     * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
     *
     * @param enabled Whether or not to watch for gestures.
     */
    public void setEnabled(boolean enabled) {
        mPaused = !enabled;
    }

    /**
     * Returns an {@link AbsListView.OnScrollListener} to be added to the {@link
     * ListView} using {@link ListView#setOnScrollListener(AbsListView.OnScrollListener)}.
     * If a scroll listener is already assigned, the caller should still pass scroll changes through
     * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is
     * paused during list view scrolling.</p>
     *
     * @see SwipeDismissListViewTouchListener
     */
    public AbsListView.OnScrollListener makeScrollListener() {
        return new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        };
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

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

        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                if (mPaused) {
                    return false;
                }

                if (focusedChild != null) {
                    ImageButton focusedEdit = (ImageButton)focusedChild.findViewById(R.id.edit);
                    ImageButton focusedDelete = (ImageButton)focusedChild.findViewById(R.id.delete);

                    pushAwayIcons(focusedEdit, focusedDelete);
                    // This needs to be done or else the translation will execute continously on
                    // retouch of focusedChild, showing considerable lag
                    focusedChild = null;
                }
                // Find the child view that was touched (perform a hit test)
                Rect rect = new Rect();
                int childCount = mListView.getChildCount();
                int[] listViewCoords = new int[2];
                mListView.getLocationOnScreen(listViewCoords);
                int x = (int) motionEvent.getRawX() - listViewCoords[0];
                int y = (int) motionEvent.getRawY() - listViewCoords[1];

                View child;

                //Uses hitboxes to detect which child is tapped. We assign focus to that child
                //in the form of mDownView = child and will do operations to that.
                for (int i = 0; i < childCount; i++) {
                    child = mListView.getChildAt(i);
                    edit = (ImageButton) child.findViewById(R.id.edit);
                    delete = (ImageButton) child.findViewById(R.id.delete);

                    //The child's hitbox. Will be the edges surrounding the child in the list
                    child.getHitRect(rect);
                    if (rect.contains(x, y)) {
                        mDownView = child;
                        break;
                    }
                }

                if (mDownView != null) {
                    //Get the starting position. To be compared with the raw X and Y values during

                    //ACTION_UP
                    mDownX = motionEvent.getRawX();
                    mDownY = motionEvent.getRawY();
                    //Position entails the location in the list
                    mDownPosition = mListView.getPositionForView(mDownView);
                    if (mCallbacks.canDismiss(mDownPosition)) {
                        //New VT object to watch the velocity of a motion
                        mVelocityTracker = VelocityTracker.obtain();
                        //Add user movement to the tracker
                        mVelocityTracker.addMovement(motionEvent);
                    } else {
                        //Can't be dismissed, ignore.
                        mDownView = null;
                    }
                }
                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;

                final View downView = mDownView;
                final int downPosition = mDownPosition;


                if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
                    dismiss = true;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = true;
                }
                if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
                    // dismiss
                    int translatedDistance =  (int)Math.round( 0.48 * mViewWidth );
                    focusedChild = downView;

                    edit.setTranslationX(translatedDistance);
                    delete.setTranslationX(translatedDistance);
                    edit.setVisibility(View.VISIBLE);
                    delete.setVisibility(View.VISIBLE);
                    edit.animate().alpha(1)
                            .translationX(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter(){
                                @Override
                                public void onAnimationEnd(Animator animation) {

                                }
                            });
                    delete.animate().alpha(1)
                            .translationX(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter(){
                                @Override
                                public void onAnimationEnd(Animator animation) {

                                }
                            });

                }
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mSwiping = false;
                edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent editEntry = new Intent(mCurrentContext, NewEntry.class);
                        editEntry.putExtra("noteType", "editExisting");
                        editEntry.putExtra("objectIndex", mDownPosition);
                        editEntry.putExtra("currentListType", mCurrentListType);
                        mCurrentContext.startActivity(editEntry);
                    }
                });

                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(mCurrentContext)
                                .setTitle("Delete Entry")
                                .setMessage("Are you sure you want to delete this entry?")
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String focusedChildID = CashList.expenseArrayList.get(mDownPosition).getM_objectID();
                                        String type = CashList.expenseArrayList.get(mDownPosition).getM_type();

                                        Log.d("ObjectID", focusedChildID);
                                        ParseQuery<ParseObject> deleteQuery = ParseQuery.getQuery(type);
                                        deleteQuery.getInBackground(focusedChildID, new GetCallback<ParseObject>() {
                                            @Override
                                            public void done(ParseObject po_toBeDeleted, ParseException e) {
                                                if (e == null){
                                                    po_toBeDeleted.deleteInBackground();
                                                    performDismiss(downView, downPosition);
                                                }
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // do nothing
                                    }
                                })
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .show();

                    }
                });

                break;
            }

            //Nts: This is repeatedly executed on ACTION_MOVE
            case MotionEvent.ACTION_MOVE: {
                if (mVelocityTracker == null || mPaused) {
                    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);
                    mListView.requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch (un-highlighting the item)
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                            (motionEvent.getActionIndex()
                                    << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mListView.onTouchEvent(cancelEvent);
                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    return true;
                }
                break;
            }

        }
        return false;
    }

    class PendingDismissData implements Comparable<PendingDismissData> {
        public int position;
        public View view;

        public PendingDismissData(int position, View view) {
            this.position = position;
            this.view = view;
        }

        @Override
        public int compareTo(PendingDismissData other) {
            // Sort by descending position
            return other.position - position;
        }
    }

    private void pushAwayIcons (final ImageButton edit, final ImageButton delete){
        int translatedDistance =  (int)Math.round( 0.48 * mViewWidth );
        edit.animate().alpha(0)
                .translationX(translatedDistance)
                .setDuration(mAnimationTime)
                .setListener(new AnimatorListenerAdapter(){
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        edit.setVisibility(View.INVISIBLE);
                        edit.setTranslationX(0);

                    }
                });
        delete.animate().alpha(0)
                .translationX(translatedDistance)
                .setDuration(mAnimationTime)
                .setListener(new AnimatorListenerAdapter(){
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        delete.setVisibility(View.INVISIBLE);
                        delete.setTranslationX(0);
                    }
                });


    }

    private void performDismiss(final View dismissView, final int dismissPosition) {
        // Animate the dismissed list item to zero-height and fire the dismiss callback when
        // all dismissed list item animations have completed. This triggers layout on each animation
        // frame; in the future we may want to do something smarter and more performant.



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

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

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                   mDownPosition = ListView.INVALID_POSITION;
            }
        });

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

        mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
        animator.start();
    }
}




Java Source Code List

com.kevinzhu.xpense.ApplicationTest.java
com.kevinzhu.xpense.CashFlowListAdapter.java
com.kevinzhu.xpense.CashFlow.java
com.kevinzhu.xpense.CashList.java
com.kevinzhu.xpense.DatePickerFragment.java
com.kevinzhu.xpense.Main.java
com.kevinzhu.xpense.NewEntry.java
com.kevinzhu.xpense.SwipeDismissListViewTouchListener.java
com.kevinzhu.xpense.Xpense.java