Custom ListView to achieve sliding deletion of items and menu Effect

Source: Internet
Author: User

Custom ListView to achieve sliding deletion of items and menu Effect

This program is modified based on an open-source project on the Internet. If you forget the specific source, you are too lazy to search for it. If there is anything inappropriate, please contact me by the original author. I will reply and handle it in time!

In this example, the program mainly contains two ListView, one is to achieve slide deletion, the other is to slide out the menu, and the comments in the Code are very complete, so I will not go into details, directly paste the core code and, at the end of the program source code, if you do not understand anything, you can leave a comment. I will reply in time. Do not spray it!

Slide to delete ListView:

Package com. example. testslidelistview; import android. content. context; import android. util. attributeSet; import android. view. motionEvent; import android. view. velocityTracker; import android. view. view; import android. view. viewConfiguration; import android. view. windowManager; import android. widget. adapterView; import android. widget. listView; import android. widget. scroller;/*** click it to delete the ListView of an Item. This is an open-source Lis Tview is perfect. * The transparency of the item changes when the finger slides, add the animation process * @ author zhangshuo */public class SlideListView extends ListView {/*** currently sliding ListView position */private int slidePosition; /*** press the coordinates of X by finger */private int downY;/*** press the coordinates of Y by finger */private int downX; /***** screen width */private int screenWidth;/***** ListView's item */private View itemView;/***** slide class */private Scroller scroller; private static final int SNAP_VELOCITY = 600;/*** speed tracking object */private VelocityTracker velocityTracker;/*** whether to respond to slide. The default value is "no response" */private boolean isSlide = false; /*** minimum sliding distance */private int mTouchSlop;/*** callback interface after item removal */private RemoveListener mRemoveListener; /*** indicates whether to remove */private boolean isRemove = false;/*** indicates the direction in which the item slides out of the screen, left or right, use an enumerated value to mark */private RemoveDirection removeDirection; // The enumerated value of the sliding Delete direction public enum RemoveDirection {RIGHT, LEFT, NONE;} public SlideListView (Context context) {this (context, null);} public SlideListView (Context context, AttributeSet attrs) {this (context, attrs, 0 );} public SlideListView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); screenWidth = (WindowManager) context. getSystemService (Context. WINDOW_SERVICE )). getdefadisplay display (). getWidth (); scroller = new Scroller (context ); MTouchSlop = ViewConfiguration. get (getContext ()). getScaledTouchSlop ();}/*** sets the sliding deletion callback interface * @ param removeListener */public void setRemoveListener (RemoveListener removeListener) {this. mRemoveListener = removeListener;}/*** distribution event, mainly used to determine the item clicked, and postDelayed to set the response to the left and right sliding event */@ Overridepublic boolean dispatchTouchEvent (MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: {S Ystem. out. println ("dispatch -->" + "down"); addVelocityTracker (event); // We will directly return if (! Scroller. isFinished () {return false;} downX = (int) event. getX (); downY = (int) event. getY (); slidePosition = pointToPosition (downX, downY); // The position is invalid and will not be processed. if (slidePosition = AdapterView. INVALID_POSITION) {return super. dispatchTouchEvent (event);} // obtain the item viewitemView = getChildAt (slidePosition-getFirstVisiblePosition (); break;} case MotionEvent. ACTION_MOVE: {System. out. println ("dispatc H --> "+" move "); if (Math. abs (getScrollVelocity ()> SNAP_VELOCITY | (Math. abs (event. getX ()-downX)> mTouchSlop & Math. abs (event. getY ()-downY) <mTouchSlop) {isSlide = true;} break;} case MotionEvent. ACTION_UP: recycleVelocityTracker (); break;} return super. dispatchTouchEvent (event);}/*** slide to the right. getScrollX () returns the distance from the left edge, that is, the distance from the left edge of the View to the start of sliding, so sliding to the right is a negative value */private void scrollRight () {removeDirection = RemoveDirection. RIGHT; final int delta = (screenWidth + itemView. getScrollX (); // call the startScroll method to set some rolling parameters. We call scrollTo in the computeScroll () method to scroll itemscroller. startScroll (itemView. getScrollX (), 0,-delta, 0, Math. abs (delta); postInvalidate (); // refresh itemView}/*** slides to the left. Based on the above information, sliding to the left is a positive value */private void scrollLeft () {removeDirection = RemoveDirection. LEFT; final int delta = (screenWidth-itemView. getScrollX () ); // Call the startScroll method to set some rolling parameters. We call scrollTo in the computeScroll () method to scroll itemscroller. startScroll (itemView. getScrollX (), 0, delta, 0, Math. abs (delta); postInvalidate (); // refresh itemView}/*** slide to the original position */private void scrollBack () {removeDirection = RemoveDirection. NONE; scroller. startScroll (itemView. getScrollX (), 0,-itemView. getScrollX (), 0, Math. abs (itemView. getScrollX (); postInvalidate (); // refresh itemView }/*** Based on the distance of the finger rolling itemView, you can determine whether to scroll to the start position or left or right */private void scrollByDistanceX () {// if the distance to the left is greater than 1/2 of the screen, let it delete if (itemView. getScrollX ()> = screenWidth/2) {scrollLeft ();} else if (itemView. getScrollX () <=-screenWidth/2) {scrollRight ();} else {// roll back to the original position scrollBack ();}} /*** process the logic of dragging the ListView item */@ Overridepublic boolean onTouchEvent (MotionEvent ev) {if (isSlide & slidePosition! = AdapterView. INVALID_POSITION) {System. out. println ("touch -->" + ""); requestDisallowInterceptTouchEvent (true); addVelocityTracker (ev); final int action = ev. getAction (); int x = (int) ev. getX (); switch (action) {case MotionEvent. ACTION_DOWN: System. out. println ("touch -->" + "down"); break; case MotionEvent. ACTION_MOVE: System. out. println ("touch -->" + "move"); MotionEvent cancelEvent = MotionEvent. obtain (ev ); CancelEvent. setAction (MotionEvent. ACTION_CANCEL | (ev. getActionIndex () <MotionEvent. ACTION_POINTER_INDEX_SHIFT); onTouchEvent (cancelEvent); int deltaX = downX-x; // scroll itemView with a finger. If deltaX is greater than 0, scroll to the left, and if it is less than 0, roll itemView to the right. scrollTo (deltaX, 0); // adjust the transparency itemView Based on the sliding distance of the finger. setAlpha (1f-Math. abs (float) deltaX/screenWidth); return true; // when dragging, ListView does not scroll case MotionEvent. ACTION_UP: System. out. println ("touch --> "+" Up "); // when the finger leaves, it does not respond to the left and right rolling isSlide = false; int velocityX = getScrollVelocity (); if (velocityX> SNAP_VELOCITY) {scrollRight ();} else if (velocityX <-SNAP_VELOCITY) {scrollLeft ();} else {scrollByDistanceX () ;}recyclevelocitytracker (); break ;}} // otherwise, it will be handed over to ListView to handle the onTouchEvent return super. onTouchEvent (ev) ;}@ Overridepublic void computeScroll () {// scroller when startScroll is called. computescroloffset () returns true, I F (scroller. computescroloffset () {// Let the ListView item scroll itemView based on the current rolling offset. scrollTo (scroller. getCurrX (), scroller. getCurrY (); itemView. setAlpha (1f-Math. abs (float) scroller. getCurrX ()/screenWidth); postInvalidate (); // call the callback interface if (scroller when the rolling animation ends. isFinished () & removeDirection! = RemoveDirection. NONE) {if (mRemoveListener = null) {throw new NullPointerException ("RemoveListener is null, we shocould called setRemoveListener ()");} itemView. scrollTo (0, 0); itemView. setAlpha (1f); mRemoveListener. removeItem (removeDirection, slidePosition) ;}}/ *** Add a user's speed tracker ** @ param event */private void addVelocityTracker (MotionEvent event) {if (velocityTracker = null) {velocityTracker = Veloci TyTracker. obtain ();} velocityTracker. addMovement (event);}/*** Remove User speed tracker */private void recycleVelocityTracker () {if (velocityTracker! = Null) {velocityTracker. recycle (); velocityTracker = null;}/*** get the sliding speed in the X direction. If the sliding speed is greater than 0, slide to the right, and vice versa to the left ** @ return */private int getScrollVelocity () {velocityTracker. computeCurrentVelocity (1000); int velocity = (int) velocityTracker. getXVelocity (); return velocity;}/***** when the ListView item slides out of the screen, the callback interface * we need to remove this Item from the callback method removeItem, then refresh the ListView ** @ author xiaanming **/public interface RemoveListener {public void removeItem (RemoveDirection direction, int position );}}
Slide menu ListView:

Package com. example. testslidelistview; import android. content. context; import android. util. attributeSet; import android. view. motionEvent; import android. view. view; import android. view. viewConfiguration; import android. widget. adapterView; import android. widget. listView; import android. widget. scroller;/*** use the lateral slide menu ListView *. Be sure to work with the layout of the ListView Item, * This effect is implemented based on setting PaddingLeft and PaddingRight in the Item layout to hide left and right menus, * When using this ListView, be sure to use PaddingLeft and PaddingRight during Item layout; * Or rewrite this ListView by yourself, the desired implementation method * @ author zhangshuo */public class SlideListView2 extends ListView {/** disable slide mode */public static int MOD_FORBID = 0; /** slide menu mode from left to right */public static int MOD_LEFT = 1;/** slide menu mode from right to left */public static int MOD_RIGHT = 2; /** the left and right menu modes can be slide out */public static int MOD_BOTH = 3;/** current mode */private int mode = MOD_FORBID; /** length of the Left menu */private int LeftLength = 0;/** length of the right menu */private int rightLength = 0;/*** currently sliding ListView position */private int slidePosition; /*** press the coordinates of X by finger */private int downY;/*** press the coordinates of Y by finger */private int downX; /*** ListView's item */private View itemView;/***** sliding class */private Scroller scroller; /*** minimum distance of user sliding */private int mTouchSlop;/*** determines whether sliding can be performed sideways */private boolean canMove = false; /*** indicates whether slide is complete */private boolean isSlide D = false; public SlideListView2 (Context context) {this (context, null);} public SlideListView2 (Context context, AttributeSet attrs) {this (context, attrs, 0 );} public SlideListView2 (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); scroller = new Scroller (context); mTouchSlop = ViewConfiguration. get (getContext ()). getScaledTouchSlop ();}/*** initialize the menu's slip mode * @ param mode */p Ublic void initSlideMode (int mode) {this. mode = mode;}/*** process the logic of dragging the ListView item */@ Overridepublic boolean onTouchEvent (MotionEvent ev) {final int action = ev. getAction (); int lastX = (int) ev. getX (); switch (action) {case MotionEvent. ACTION_DOWN: System. out. println ("touch -->" + "down");/* if the current mode does not allow sliding, the system returns the result directly and submits it to the ListView for processing */if (this. mode = MOD_FORBID) {return super. onTouchEvent (ev);} // if it is in the completed slide status, slide back and Directly return if (isSlided) {scrollBack (); return false ;}// if scroller is not finished yet, we will return if (! Scroller. isFinished () {return false;} downX = (int) ev. getX (); downY = (int) ev. getY (); slidePosition = pointToPosition (downX, downY); // The position is invalid and will not be processed. if (slidePosition = AdapterView. INVALID_POSITION) {return super. onTouchEvent (ev);} // get the item viewitemView = getChildAt (slidePosition-getFirstVisiblePosition () We clicked;/* Based on the set slide mode, automatically obtain the length of the Left or Right menu */if (this. mode = MOD_BOTH) {this. leftLength =-itemV Iew. getPaddingLeft (); this. rightLength =-itemView. getPaddingRight ();} else if (this. mode = MOD_LEFT) {this. leftLength =-itemView. getPaddingLeft ();} else if (this. mode = MOD_RIGHT) {this. rightLength =-itemView. getPaddingRight ();} break; case MotionEvent. ACTION_MOVE: System. out. println ("touch -->" + "move"); if (! CanMove & slidePosition! = AdapterView. INVALID_POSITION & (Math. abs (ev. getX ()-downX)> mTouchSlop & Math. abs (ev. getY ()-downY) <mTouchSlop) {int offsetX = downX-lastX; if (offsetX> 0 & (this. mode = MOD_BOTH | this. mode = MOD_RIGHT) {/* slide from right to left */canMove = true;} else if (offsetX <0 & (this. mode = MOD_BOTH | this. mode = MOD_LEFT) {/* slide from left to right */canMove = true;} else {canMove = false ;} /* This code segment is used to avoid the OnItemClickListener time */MotionEvent cancelEvent = MotionEvent of ListView while moving sideways. obtain (ev); cancelEvent. setAction (MotionEvent. ACTION_CANCEL | (ev. getActionIndex () <MotionEvent. ACTION_POINTER_INDEX_SHIFT); onTouchEvent (cancelEvent);} if (canMove) {/* sets this attribute to keep the ListView from scrolling up or down */requestDisallowInterceptTouchEvent (true) When sliding sideways ); // drag itemView with your finger to scroll. deltaX is greater than 0 to scroll to the left, and int deltaX = downX-lastX is rolled to the right if (deltaX <0 & (this. mode = MOD_BOTH | this. mode = MOD_LEFT) {/* slide to the left */itemView. scrollTo (deltaX, 0);} else if (deltaX> 0 & (this. mode = MOD_BOTH | this. mode = MOD_RIGHT) {/* slide to the right */itemView. scrollTo (deltaX, 0);} else {itemView. scrollTo (0, 0);} return true; // when dragging, ListView does not scroll} case MotionEvent. ACTION_UP: System. out. println ("touch -->" + "up"); if (canMove) {canMove = false; scrollByDistanceX ();} break ;} // otherwise, it will be handed over to ListView to handle the onTouchEvent return super. onTouchEvent (ev);}/*** determines whether to scroll to the start position or left or right based on the itemView distance of the finger */private void scrollByDistanceX () {/* if (this. mode = MOD_FORBID) {return;} if (itemView. getScrollX ()> 0 & (this. mode = MOD_BOTH | this. mode = MOD_RIGHT) {/* slide from right to left */if (itemView. getScrollX () >=rightlength/2) {scrollLeft () ;}else {// roll back to the original position scrollBack () ;}} else if (itemView. getScrollX () <0 & (this. mode = MOD_BOTH | this. mode = MOD_LEFT) {/* slide from left to right */if (itemView. getScrollX () <=-leftLength/2) {scrollRight ();} else {// roll back to the original position scrollBack ();}} else {// roll back to the original position scrollBack () ;}/ *** slide to the right. getScrollX () returns the distance from the left edge, it is the distance from the left edge of the View to the start of sliding, so sliding to the right is a negative value */private void scrollRight () {isSlided = true; final int delta = (leftLength + itemView. getScrollX (); // call the startScroll method to set some rolling parameters. We call scrollTo in the computeScroll () method to scroll itemscroller. startScroll (itemView. getScrollX (), 0,-delta, 0, Math. abs (delta); postInvalidate (); // refresh itemView}/*** slides to the left. Based on the above information, sliding to the left is a positive value */private void scrollLeft () {isSlided = true; final int delta = (rightLength-itemView. getScrollX (); // call the startScroll method to set some rolling parameters. We call scrollTo in the computeScroll () method to scroll itemscroller. startScroll (itemView. getScrollX (), 0, delta, 0, Math. abs (delta); postInvalidate (); // refresh itemView}/*** slide to the original position */private void scrollBack () {isSlided = false; scroller. startScroll (itemView. getScrollX (), 0,-itemView. getScrollX (), 0, Math. abs (itemView. getScrollX (); postInvalidate (); // refresh itemView} @ Overridepublic void computeScroll () {// scroroller when startScroll is called. computescroloffset () returns true, if (scroller. computescroloffset () {// Let the ListView item scroll itemView based on the current rolling offset. scrollTo (scroller. getCurrX (), scroller. getCurrY (); postInvalidate () ;}/ *** is provided to external calls to slide the slide back */public void slideBack () {this. scrollBack ();}}

Note that the use of the slide menu ListView must work with the Item layout (mainly the PaddingLeft and PaddingRight attributes). The Item layout is as follows:

     
          
               
            
           
               
            
       
          
          
           
            
            
        
       
           
                
             
            
                
             
        
       
      
 
:

: Http://download.csdn.net/detail/super_spy/7667793


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.