Android Swipetodismiss: Zoli/Right Slide delete ListView entry Item

Source: Internet
Author: User



"Android Swipetodismiss: Swipe left and right to delete a ListView entry item"

Android Swipetodismiss is the third party open source framework on GitHub (Project link address on GitHub: Https://github.com/romannurik/Android-SwipeToDismiss). The Open source project is designed to make a ListView item delete the current ListView item when the user's finger slides left or right on the screen.
This kind of effect in the new version of Android, such as in Android 5.0 and above, the notification bar drop-down menu entry, is the effect of this action, the user put the notification bar under the pull, the finger touch an item, left or right slide, delete (clear) this item.
There are two files downloaded to the library in Https://github.com/romannurik/Android-SwipeToDismiss (this is based on the version as of July 27, 2015, Subsequent versions may vary): Swipedismisslistviewtouchlistener.java and Swipedismisstouchlistener.java. If just intended simply to support a ListView list with item Left/right sliding delete, then just import swipedismisslistviewtouchlistener.java this one library file.
Now give a simple example of how to transform a standard ListView so that it supports sliding an item around and then deleting it.


Mainactivity.java for testing:

Package Zhangphil.listview;import Java.util.arraylist;import Android.app.listactivity;import android.os.Bundle; Import Android.util.log;import Android.widget.arrayadapter;import Android.widget.listview;public class MainActivity Extends Listactivity {private arrayadapter<string> adapter = null;private arraylist<string> items = null;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); ListView ListView = This.getlistview ();//test data set. Items = new arraylist<string> (); for (int i = 0; i < i++) {Items.Add ("data:" + i);} adapter = new Arrayadapter<string> (this,android. R.layout.simple_list_item_1, items); Listview.setadapter (adapter);//Pass the ListView over. Swipedismisslistviewtouchlistener Touchlistener = new Swipedismisslistviewtouchlistener (listView,new Swipedismisslistviewtouchlistener.dismisscallbacks () {@Overridepublic boolean candismiss (int position) {return true;} Delete will be performed here, remember to notifydatasetchanged (). @Overridepublic void OndismiSS (ListView listview,int[] reversesortedpositions) {for (int pos:reversesortedpositions) {items.remove (POS); LOG.I (This.getclass (). GetName (), "Delete:" + pos);} Adapter.notifydatasetchanged ();}}); Listview.setontouchlistener (Touchlistener);}}


Required Library Files Swipedismisslistviewtouchlistener.java:

/* * Copyright Google INC * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applic Able law or agreed to in writing, software * Distributed under the License are distributed on a "as is" BASIS, * without W Arranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Zhangphil.listview;import Android.animation.animator;import Android.animation.AnimatorListenerAdapter; Import Android.animation.valueanimator;import Android.graphics.rect;import Android.os.systemclock;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.listview;import Java.util.arraylist;import java.util.Collections; 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 it list items ... i.e. it's in * C Harge of drawing the pressed state (the list selector), handling list item * Clicks, etc. * * <p> * after creating t He listener, the caller should also call * {@link Listview#setonscrolllistener (Abslistview.onscrolllistener)}, passing * I n 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 would ensure this * {@link Swipedismisslistviewtouchlistener} is paused during List view * scrolling. * </p> * * <p> * Example Usage: * </p> * * <pre> * SwipedismisslistviewtouchlistenerTouchlistener = 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/later due to use of * {@link viewpropertyanimator}. * </p> * * <p> * for a generalized {@link View.ontouchlistener} that makes any View * dismissable, see {@link Swipedismisstouchlistener}. * </p> * * @see Swipedismisstouchlistener */public class Swipedismisslistviewtouchlistener implements View.ontouchlistener {//Cached viewconfiguration and System-wide constant valuesprivate int mslop;private int MMINFLINGV elocity;private int Mmaxflingvelocity;privaTe long manimationtime;//Fixed propertiesprivate ListView mlistview;private dismisscallbacks mcallbacks;private int Mviewwidth = 1; 1 and not 0 to prevent dividing by zero//Transient propertiesprivate list<pendingdismissdata> mpendingdismisses = new Arraylist<pendingdismissdata> ();p rivate int mdismissanimationrefcount = 0;private float mDownX;private Float mdowny;private boolean mswiping;private int mswipingslop;private velocitytracker mvelocitytracker;private int Mdownposition;private View Mdownview;private Boolean mpaused;/** * The callback interface used by {@link Swipedismisslistv Iewtouchlistener} to inform it client about a successful dismissal the one or more list * Item positions. */public interface Dismisscallbacks {/** * Called to determine whether the given position can be dismissed. */boolean Cand Ismiss (int position);/** * Called when the user had indicated they she would like to dismiss one * or more list item posit Ions. * * @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 had indicated that she * would as to Di Smiss one or more list items. */public Swipedismisslistviewtouchlistener (ListView listview,dismisscallbacks callbacks) {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;} /** * 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 a {@link abslistview.onscrolllistener} to being added to the * {@link ListView} using * {@link listview#setons Crolllistener (Abslistview.onscrolllistener)}. If A * Scroll listener is already assigned, the caller should still pass scroll * changes through to this listener.  This would ensure the this * {@link Swipedismisslistviewtouchlistener} is paused during list view * scrolling.</p> * * @see Swipedismisslistviewtouchlistener */public abslistview.onscrolllistener Makescrolllistener () {return new Abslistview.onscrolllistener () {@Overridepublic void onscrollstatechanged (Abslistview abslistview,int scrollstate) { SetEnabled (scrollstate! = AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);} @Overridepublic void Onscroll (Abslistview abslistview, INT I, int i1, int i2) {}};} @Overridepublic Boolean OnTouch (View view, Motionevent motionevent) {if (Mviewwidth < 2) {mviewwidth = Mlistview.getwid Th ();} Switch (motionevent.getactionmasked ()) {case Motionevent.action_down: {if (mpaused) {return false;} Todo:ensure This is a finger, and set a flag//Find the child view that's touched (perform a hit test) rect rect = NE W 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 ()-Listviewcoor DS[1]; View child;for (int i = 0; i < ChildCount; i++) {child = Mlistview.getchildat (i); Child.gethitrect (rect); if (Rect.contai NS (x, y)) {mdownview = Child;break;}} if (Mdownview! = null) {Mdownx = Motionevent.getrawx (); mdowny = Motionevent.getrawy (); mdownposition = Mlistview.getpositionforview (Mdownview); if (Mcallbacks.candismiss (mdownposition)) {Mvelocitytracker = velocitytracker.oBtain (); mvelocitytracker.addmovement (motionevent);} else {mdownview = null;}} return false;} Case Motionevent.action_cancel: {if (mvelocitytracker = = null) {break;} if (Mdownview! = null && mswiping) {//Cancelmdownview.animate (). Translationx (0). Alpha (1). Setduration ( manimationtime). Setlistener (null);} Mvelocitytracker.recycle (); mvelocitytracker = Null;mdownx = 0;mdowny = 0;mdownview = Null;mdownposition = listview.invalid_position;mswiping = False;break;} Case MOTIONEVENT.ACTION_UP: {if (mvelocitytracker = = null) {break;} float deltax = motionevent.getrawx ()-mdownx;mvelocitytracker.addmovement (motionevent); Mvelocitytracker.computecurrentvelocity (+); 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 & Gt 0;} else if (MminflingveLocity <= absvelocityx&& Absvelocityx <= mmaxflingvelocity&& AbsVelocityY < AbsVelocityX &  & mswiping) {//dismiss only if flinging in the same direction as Draggingdismiss = (Velocityx < 0) = = (DeltaX < 0);d ismissright = mvelocitytracker.getxvelocity () > 0;} if (Dismiss && mdownposition! = listview.invalid_position) {//dismissfinal View Downview = mdownview;//Mdownvie W gets null ' d before//animation endsfinal int downposition = Mdownposition;++mdismissanimationrefcount; Mdownview.animate (). Translationx (dismissright mviewwidth:-mviewwidth). Alpha (0). Setduration (Manimationtime). Setlistener (New Animatorlisteneradapter () {@Overridepublic void Onanimationend (Animator animation) {Performdismiss ( Downview, downposition);});} else {//Cancelmdownview.animate (). Translationx (0). Alpha (1). Setduration (Manimationtime). Setlistener (null);} Mvelocitytracker.recycle (); mvelocitytracker = Null;mdownx = 0;mdowny = 0;mdownview = Null;mdownposition = ListVIew. invalid_position;mswiping = False;break;} 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) {MSw  iping = 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) {Mdownview.settranslationx (deltax-mswipingslop); Mdownview.setalpha (Math.max (0f,Math.min (1f, 1f-2f * Math.Abs (deltax)/mviewwidth)); 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;} @Overridepublic int CompareTo (Pendingdismissdata other) {//Sort by descending positionreturn other.position-position;} }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 has completed. This triggers//layout on each animation//frame; In the future we could want to do something smarter and more//performant.final viewgroup.layoutparams LP = Dismissview.getl Ayoutparams (); final int originalheight = Dismissview.getheight (); Valueanimator animator = Valueanimator.ofint (OriginalHeight, 1). Setduration (Manimationtime); Animator.addlistener ( New Animatorlisteneradapter () {@Overridepublic void Onanimationend (Animator animation) {--mdismissanimationrefcount; if (Mdismissanimationrefcount = = 0) {//No Active animations, process all pending dismisses.//Sort by descending positioncollections.sort (mpendingdismisses); int [] dismisspositions = new Int[mpendingdismisses.size ()];for (int i = Mpendingdismisses.size ()-1; I >= 0; i--) {Dismis Spositions[i] = Mpendingdismisses.get (i). Position;} Mcallbacks.ondismiss (Mlistview, dismisspositions);//Reset mdownposition to avoid motionevent.action_up trying//to Start a dismiss//animation with a stale positionmdownposition = listview.invalid_position; Viewgroup.layoutparams lp;for (Pendingdismissdata pendingdismiss:mpendingdismisses) {//Reset view PresentationpendingDismiss.view.setAlpha (1f);p EndingDismiss.view.setTranslationX (0); LP = PendingDismiss.view.getLayoutParams (); lp.height = ORIGINALHEIGHT;PENDINGDISMISS.VIEW.SETLAYOUTPARAMS (LP);} Send a Cancel Eventlong time = Systemclock.uptimemillis (); Motionevent CancelEvent = Motionevent.obtain (time, time,motionevent.action_cancel, 0, 0, 0); Mlistview.dispatchtouchevent (CancelEvent); mpendingdIsmisses.clear ();}}); Animator.addupdatelistener (New Valueanimator.animatorupdatelistener () {@Overridepublic void Onanimationupdate ( Valueanimator valueanimator) {lp.height = (Integer) valueanimator.getanimatedvalue ();d ISMISSVIEW.SETLAYOUTPARAMS (LP );}}); Mpendingdismisses.add (New Pendingdismissdata (Dismissposition,dismissview)); Animator.start ();}}


Directory structure:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Swipetodismiss: Zoli/Right Slide delete ListView entry Item

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.