Detailed Android to achieve ListView left-right Sliding Delete entry method _android

Source: Internet
Author: User
Tags abs gety

use Scroller to implement the gorgeous ListView sliding Delete Item Effect
Here's a little example of using scroller, At the same time can also be used to help the initial release of the reader more familiar with the use of scroller mastered the use of scroller, we can achieve a lot of sliding effect. For example, sideslip menu, Launcher,listview drop-down Refresh, and so on, I realized today is the ListView item's left and right sliding delete item effect, Now many friends see this effect should be in the Android notice bar Drop-down to see the effect of the sliding delete it, I see this effect is in my previous Samsung mobile phone to slide around the effect of the phone to send text messages, it feels great, but now many mobile phone contact slip is not the effect of my previous mobile phone, A lot of friends on the Internet also wrote about the slide delete ListView Item example, some is sliding the finger left and then to the item add left or right movement animation, I think this kind of user experience is not very good, So today I wrote a small example of listview about sliding Delete item, the item of ListView will slide with the slide of the finger on the screen, when the finger leaves the screen, the item will draw the screen to the left or right according to the judgment, which is similar to the effect of the notice bar. The next step is to bring you to this effect.
First of all, the main idea to achieve this effect
is to get a click on the point where the finger touches the ListView the item
Finger is sliding on the screen we use Scrollby () to slide the item along with the finger
when the finger is released, We determine the distance the finger is dragged to determine whether the item is sliding out of the screen or back to the beginning.
The main idea is the above three steps, then we use code to achieve it, first of all, we create a new project, called Slidecutlistview
According to the requirements we need to customize a ListView to implement this function, and then post the code to explain the implementation of the specific

Package Com.example.slidecutlistview; 
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; 
  public class Slidecutlistview extends ListView {/** * currently sliding ListView position * * private int slideposition; 
  /** * Finger Press x coordinates */private int downY; 
  /** * Finger Press Y coordinates * * * private int downx; 
  /** * Screen width */private int screenwidth; 
  /** * ListView of the item * * * Private View Itemview; 
  /** * Sliding class * * private scroller scroller; 
  private static final int snap_velocity = 600; 
  /** * Speed Tracking object/private Velocitytracker velocitytracker; 
  /** * Whether the response is sliding, the default is not response * * Private Boolean isslide = false; /** * The minimum distance that the user is sliding */private int mtouchslop; 
  /** * Remove the callback interface after item * * Private RemoveListener Mremovelistener; 
 
  /** * is used to instruct the item to slide out of the screen direction, to the left or right, with an enumeration value to mark/private removedirection removedirection; 
  The enumeration value that slides the deletion direction public enum Removedirection {right, left; 
  The public Slidecutlistview {This (context, NULL); 
  Public Slidecutlistview (context, AttributeSet attrs) {This (context, attrs, 0); 
    Public Slidecutlistview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); 
    ScreenWidth = ((WindowManager) Context.getsystemservice (Context.window_service)). Getdefaultdisplay (). GetWidth (); 
    Scroller = new Scroller (context); 
  Mtouchslop = Viewconfiguration.get (GetContext ()). Getscaledtouchslop (); /** * Set the callback interface for sliding deletion * @param removelistener */public void Setremovelistener (RemoveListener removeli 
  Stener) {this.mremovelistener = RemoveListener; 
 }
  /** * Distribution of events, mainly do is to determine the click of the item, as well as through the postdelayed to set response to the left and right sliding event/@Override public boolean dispatchtouchevent (M Otionevent event) {switch (event.getaction ()) {case Motionevent.action_down: {Addvelocitytracker (Event 
 
      ); 
      If the scroller scroll has not finished, we directly return if (!scroller.isfinished ()) {returns super.dispatchtouchevent (event); 
      } DOWNX = (int) event.getx (); 
 
      DownY = (int) event.gety (); 
 
      Slideposition = Pointtoposition (Downx, DownY); Invalid POSITION, do not do any processing if (slideposition = = adapterview.invalid_position) {return Super.dispatchtoucheven 
      T (event); 
      //Get the item view we clicked Itemview = Getchildat (Slideposition-getfirstvisibleposition ()); 
    Break Case Motionevent.action_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, which is the distance from the left edge of the view to the beginning of the slide, so slide to the right for negative/private void scrollright () { 
    Removedirection = Removedirection.right; 
    Final int delta = (screenwidth + ITEMVIEW.GETSCROLLX ()); Call the Startscroll method to set some scrolling parameters, we call Scrollto in the Computescroll () method to scroll the item scroller.startscroll (ITEMVIEW.GETSCROLLX (), 0 
    ,-delta, 0, Math.Abs (delta)); Postinvalidate (); Refresh Itemview}/** * Slide to the left, according to the above we know to slide to the left is positive * * private void ScrollLeft () {removedirection = Remove 
    Direction.left; 
    Final int delta = (SCREENWIDTH-ITEMVIEW.GETSCROLLX ()); Call the Startscroll method to set some scrolling parameters, we call Scrollto in the Computescroll () method to scroll the item scroller.startscroll (ITEMVIEW.GETSCROLLX (), 0 
    , Delta, 0, Math.Abs (delta)); PostiNvalidate (); 
    Refresh Itemview}/** * To determine whether to scroll to the starting position or to the left or to the right, depending on the distance of the finger scrolling itemview (* * * * private void Scrollbydistancex () { 
    If the distance to scroll to the left is greater than one-second of the screen, let it delete if (ITEMVIEW.GETSCROLLX () >= screenwidth/2) {scrollleft (); 
    else if (ITEMVIEW.GETSCROLLX () <=-screenwidth/2) {scrollright (); 
    else {//Roll back to original position, in order to steal the sloth here is the direct call Scrollto scrolling itemview.scrollto (0, 0); }/** * Handle the logic of our Drag ListView Item/@Override public boolean ontouchevent (motionevent ev) {i 
      F (isslide && slideposition!= adapterview.invalid_position) {requestdisallowintercepttouchevent (true); 
      Addvelocitytracker (EV); 
      Final int action = Ev.getaction (); 
      int x = (int) ev.getx (); 
      Switch (action) {case MotionEvent.ACTION_DOWN:break; 
        Case MotionEvent.ACTION_MOVE:MotionEvent CancelEvent = motionevent.obtain (EV); Cancelevent.setaction (Motionevent.action_CANCEL | 
        (Ev.getactionindex () << motionevent.action_pointer_index_shift)); 
         
        Ontouchevent (CancelEvent); 
        int deltax = downx-x; 
 
        Downx = x; 
         
        Finger Drag itemview Scrolling, DeltaX greater than 0 to the left, less than 0 to the right roll Itemview.scrollby (deltax, 0); return true; 
        Drag when ListView not scroll case MotionEvent.ACTION_UP:int Velocityx = getscrollvelocity (); 
        if (Velocityx > Snap_velocity) {scrollright (); 
        else if (Velocityx <-snap_velocity) {scrollleft (); 
        else {Scrollbydistancex (); 
        } recyclevelocitytracker (); 
        When the finger leaves, does not respond to the left and right scroll isslide = false; 
      Break 
  }//otherwise directly to ListView to handle the Ontouchevent event return super.ontouchevent (EV); The Scroller.computescrolloffset () returns True when @Override public void Computescroll () {//Startscroll is invoked, if (s Croller.computescrolloffset ()) {//Let ListView item scroll according to the current scrolling offset itemview.scrollto (Scroller.getcurrx (), Scroller.getcurry ()); 
 
      Postinvalidate (); Call the callback interface if (scroller.isfinished ()) {if (Mremovelistener = = null) {throw new Nullpo at the end of the scrolling animation 
        Interexception ("RemoveListener is null, we should called Setremovelistener ()"); 
        } itemview.scrollto (0, 0); 
      Mremovelistener.removeitem (Removedirection, slideposition); /** * Add user's Speed Tracker * * @param event/private void Addvelocitytracker (Motionevent eve 
    NT) {if (Velocitytracker = null) {Velocitytracker = Velocitytracker.obtain (); 
  } velocitytracker.addmovement (event); /** * Remove User speed Tracker */private void Recyclevelocitytracker () {if (Velocitytracker!= null) {ve 
      Locitytracker.recycle (); 
    Velocitytracker = null; 
 }/** * Gets the slide speed in the x direction, which is greater than 0 to the right, whereas to the left * * @return private int getscrollvelocity () {velocitytracker.computecurrentvelocity (1000); 
    int velocity = (int) velocitytracker.getxvelocity (); 
  return velocity; /** * * When ListView Item slides out of the screen, callback this interface * We need to remove the item in the callback method RemoveItem (), and then refresh the listview * * @author XIAA nming * */public interface RemoveListener {public void RemoveItem (removedirection direction, int positio 
  n); 

 } 
 
}

First we rewrite the Dispatchtouchevent () method, which is the distribution method of the event, where we only do some simple steps, and when we press the screen, if an item is rolling, We directly hand over the distribution event to the parent class of Slidecutlistview, or use pointtoposition (int x, int y) to get the click of the ListView position according to the x,y coordinates of the click. In order to get the view of the item we need to slide, we also add the sliding speed detection in this method, and judge whether to respond to the left and right movement of the item in the Action_move, and use Isslide to record whether or not to respond to the left-right sliding
And then rewrite the Ontouchevent () method, we first Judge Isslide to be true, and we click on the valid position above ListView, Otherwise directly to Slidecutlistview's parent class is ListView to process, in Action_move call Scrollby () to move the Item,scrollby () is relative to the item's previous position to move, So we're going to subtract the distance from the previous position and assign it to the Scrollby () method each time we move it. This way we achieve the smooth movement of the item, and when we lift the finger, we first determine whether the item is sliding out of the screen or sliding to the original position, depending on the speed at which the finger slides. If the speed to the right is greater than the snap_velocity,item we set, call the Scrollright () method to roll out the screen, and if the left speed is less than-snap_velocity, call ScrollLeft () to the left to roll out the screen, If we move the item slowly, we call the Scrollbydistancex () method to determine if we are rolling to that location.
In the Scrollright () and ScrollLeft () methods we use the Startscroll () method of the Scroller class to set the scrolling parameters and then invoke Postinvalidate () to refresh the interface. Interface refresh will call the Computescroll () method, we are in the process of scrolling logic on the line, it is worth mentioning the Computescroll () inside the code

Itemview.scrollto (0, 0); 

We need to scroll this item to the point at (0, 0) because we just scrolled the ListView item out of the screen and didn't remove the item, and we can't manually call Removeview () to remove the item from the ListView. We can only change the ListView data and then refresh the ListView by Notifydatasetchanged (), so we need to scroll it to (0, 0), which is more critical. The
defines the ListView that we're sliding around, then we use it, the layout is simple, a relativelayout wraps our custom listview

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" 
  xmlns:tools= "http:// Schemas.android.com/tools " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android:background= "@android: Color/darker_gray" > 
 
  <com.example.slidecutlistview.slidecutlistview 
    android:id= "@+id/slidecutlistview" 
    android:layout_width= "match_parent" 
    android:layout_height= " Match_parent "  
    android:listselector=" @android: color/transparent " 
    android:divider=" @drawable/reader_ Item_divider " 
    android:cachecolorhint=" @android: Color/transparent "> 
  </ Com.example.slidecutlistview.slidecutlistview> 
 
</RelativeLayout> 

Next, let's look at the layout of ListView's item.

<?xml version= "1.0" encoding= "UTF-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" fill_parent " 
  android:layout_height=" wrap_content "> 
 
  < LinearLayout 
    android:layout_width= "fill_parent" 
    android:layout_height= "Wrap_content" 
    android: background= "@drawable/friendactivity_comment_detail_list2" > 
 
    <textview 
      android:id= "@+id/list_item " 
      android:layout_width=" match_parent " 
      android:layout_height=" wrap_content " 
      android:layout_ margin= "15dip"/> 
  </LinearLayout> 
 
</LinearLayout> 

Remember when I mentioned in the previous article that calling the Scrollto () method scrolls through the inside of a child view, rather than scrolling through the entire layout, so we use LinearLayout to cover the layout of our item, which needs to be noted, Otherwise the rolling is just textview.
Main Page mainactivity inside the code is relatively simple, inside the use is arrayadapter, I believe we can understand

Package Com.example.slidecutlistview; 
Import java.util.ArrayList; 
 
Import java.util.List; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.widget.AdapterView; 
Import Android.widget.AdapterView.OnItemClickListener; 
Import Android.widget.ArrayAdapter; 
 
Import Android.widget.Toast; 
Import com.example.slidecutlistview.SlideCutListView.RemoveDirection; 
 
Import Com.example.slidecutlistview.SlideCutListView.RemoveListener; 
  public class Mainactivity extends activity implements removelistener{private Slidecutlistview Slidecutlistview; 
  Private arrayadapter&lt;string&gt; adapter; 
 
  Private list&lt;string&gt; datasourcelist = new arraylist&lt;string&gt; (); 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_main); 
  Init (); private void Init () {Slidecutlistview = (Slidecutlistview) Findviewbyid (R.id.slidecutliStview); 
     
    Slidecutlistview.setremovelistener (this);  
    for (int i=0; i&lt;20; i++) {datasourcelist.add ("slide Delete" + i); 
    } adapter = new Arrayadapter&lt;string&gt; (this, R.layout.listview_item, R.id.list_item, datasourcelist); 
     
    Slidecutlistview.setadapter (adapter); Slidecutlistview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (ADAP Terview&lt;?&gt; Parent, view view, int position, long id) {Toast.maketext (Mainactivity.this, Datasou 
      Rcelist.get (position), Toast.length_short). Show (); 
  } 
    }); }//Sliding callback method after deletion @Override public void RemoveItem (removedirection direction, int position) {Adapter.re 
    Move (Adapter.getitem (position)); 
      switch (direction) {case RIGHT:Toast.makeText (this, "delete right" + position, Toast.length_short). Show (); 
    Break Case LEFT:Toast.makeText (this, "delete left" + position, Toast.length_short). ShoW (); 
 
    Break 
    Default:break; 
 } 
     
  }   
 
 
}

This needs to be set on the Slidecutlistview RemoveListener, and then we removeitem in the callback method (removedirection direction, int position) To delete the position data in the call Notifydatasetchanged () Refresh ListView, I am here to use the Arrayadatper, directly call Remove () on it.
All the code is written, let's run the program to see the effect.

use Nineoldandroids to achieve gorgeous ListView left and right Delete item effect
To give us a ListView left and right to remove the item effect of the example, the above use is a sliding class scroller to achieve, but saw the next notification bar left and right sliding delete effect, is really good, when we slide item more than half of the time, the item transparency becomes 0, We knew that the item was removed when we lifted the finger. When the item transparency is not 0, we lift the finger item will return to the starting position, so that we know where to drag the item will be deleted, where the item is not deleted, the user experience better, there is an effect, Is that we slide deleted item, listview Other item will appear up or down scrolling effect, feel good, so in GitHub above search, found that a lot of open source Library has this effect, such as listviewanimations, Android-swipelistview and so on, I looked at the implementation of the principle of the use of Jake Wharton animation Open Source Library Nineoldandroids, what is this library do? In API3.0 (Honeycomb), the SDK adds a android.animation package, which is the class that implements the animation effect, and the honeycomb API enables very complex animation effects. But if developers want to use this set of APIs below 3.0, they will need to use the open source framework nine old androids, in which the SDK version is judged according to the machine we are running, and if it is API3.0 above, use the Android animation class, otherwise use the nine Old Androids Library, this is a compatible library, then let's take a look at the actual implementation of this effect


The main idea of realizing the effect


First click on the point to touch the finger to get the ListView which item


When the finger slides over the screen, we have to make the item slide with the finger sliding


When we lift our fingers, we judge whether the item is sliding out of the screen or sliding to the spot, depending on the distance of the slide or the speed of the finger on the screen.


When item slides out of the screen, the other item on the ListView produces an upward squeeze or downward squeeze.


General thinking this is the four steps, some of the details of which I will answer each of you, and then we will use the code to achieve this effect


First we create a new project, called Swipedismisslistview, we need to nine old androids this library into the project, we can go to https://github.com/JakeWharton/ Nineoldandroids download, you can use the jar package, you can also use the form of engineering library into our own projects, we also need to customize a ListView, we first look at the code and then explain the specific function of the implementation

Package Com.example.swipedismisslistview; 
Import static Com.nineoldandroids.view.ViewHelper.setAlpha; 
Import static Com.nineoldandroids.view.ViewHelper.setTranslationX; 
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.ViewGroup; 
Import Android.widget.AdapterView; 
 
Import Android.widget.ListView; 
Import Com.nineoldandroids.animation.Animator; 
Import Com.nineoldandroids.animation.AnimatorListenerAdapter; 
Import Com.nineoldandroids.animation.ValueAnimator; 
Import Com.nineoldandroids.view.ViewHelper; 

Import Com.nineoldandroids.view.ViewPropertyAnimator; 
  The public class Swipedismisslistview extends ListView {/** * is considered to be the minimum distance the user is sliding/private int mslop; 
  /** * Sliding Minimum speed * * private int mminflingvelocity; 
  /** * Sliding Maximum speed * * private int mmaxflingvelocity; /** * To perform animationTime */protected long manimationtime = 150; 
  /** * is used to mark whether the user is sliding in the * * Private Boolean mswiping; 
  /** * Sliding Speed detection category * * Private velocitytracker Mvelocitytracker; 
  /** * Finger pressed position * * private int mdownposition; 
  /** * Press the item corresponding view * * Private view mdownview; 
  private float Mdownx; 
  private float Mdowny; 
  /** * The width of the item * * * private int mviewwidth; 
 
  /** * When ListView item slips out of interface callback interface * * Private ondismisscallback ondismisscallback; /** * Set Animation time * * @param manimationtime */public void Setmanimationtime (long manimationtime) {thi 
  S.manimationtime = Manimationtime; /** * Settings Delete Callback interface * * @param ondismisscallback/public void Setondismisscallback (ONDISMISSCALLBAC 
  K ondismisscallback) {this.ondismisscallback = Ondismisscallback; 
  The public Swipedismisslistview {This (context, NULL); Public Swipedismisslistview (Context conText, AttributeSet attrs) {This (context, attrs, 0); Public Swipedismisslistview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, 
 
    Defstyle); 
    Viewconfiguration VC = viewconfiguration.get (context); 
    Mslop = Vc.getscaledtouchslop (); Mminflingvelocity = vc.getscaledminimumflingvelocity () * 8; Gets the minimum speed of the slide mmaxflingvelocity = vc.getscaledmaximumflingvelocity (); Gets the maximum sliding speed} @Override public boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {C 
      ASE MotionEvent.ACTION_DOWN:handleActionDown (EV); 
    Break 
    Case MotionEvent.ACTION_MOVE:return handleactionmove (EV); 
      Case MotionEvent.ACTION_UP:handleActionUp (EV); 
    Break 
  return super.ontouchevent (EV); 
    /** * Press Event processing * @param EV * @return/private void Handleactiondown (Motionevent ev) { 
    Mdownx = Ev.getx (); 
     
    Mdowny = Ev.gety (); MdowNposition = pointtoposition ((int) mdownx, (int) mdowny); 
    if (mdownposition = = adapterview.invalid_position) {return; 
 
    } Mdownview = Getchildat (Mdownposition-getfirstvisibleposition ()); 
    if (Mdownview!= null) {mviewwidth = Mdownview.getwidth (); 
    }//Add speed detection Mvelocitytracker = Velocitytracker.obtain (); 
  Mvelocitytracker.addmovement (EV); /** * method of handling finger sliding * * @param EV * @return/private Boolean handleactionmove (motionevent 
    EV {if (Mvelocitytracker = null | | mdownview = = NULL) {return super.ontouchevent (EV); 
    //Get the X-direction sliding distance float DeltaX = ev.getx ()-mdownx; 
 
    float DeltaY = ev.gety ()-mdowny; 
      The distance in the x direction is greater than the mslop and the Y-direction slide is less than mslop, indicating that it can slide if (math.abs (deltax) &gt; Mslop &amp;&amp; math.abs (DeltaY) &lt; Mslop) { 
       
      Mswiping = true; When the finger slides the item, cancels item's Click event, otherwise we slide item also accompanies the item clicks the occurrence motionevent CancelEvent = Motionevent.obtAin (EV); 
            Cancelevent.setaction (Motionevent.action_cancel | 
      (Ev.getactionindex () &lt;&lt; motionevent.action_pointer_index_shift)); 
    Ontouchevent (CancelEvent); 
      } if (mswiping) {//with whom the finger moves the item Viewhelper.settranslationx (Mdownview, deltax); 
 
      Transparency Gradient Viewhelper.setalpha (Mdownview, Math.max (0f, Math.min (1f, 1f-2f * Math.Abs (deltax)/mviewwidth)); 
    When the finger slides, returns True, indicating that Swipedismisslistview handles ontouchevent on its own, and that the other is given to the parent class to handle return true; 
 
  return super.ontouchevent (EV); /** * finger-raised event handling * @param EV/private void Handleactionup (Motionevent ev) {if (mvelocitytrack ER = = NULL | | Mdownview = = null| | 
    !mswiping) {return; 
     
    float deltax = Ev.getx ()-mdownx; 
    The Velocity mvelocitytracker.computecurrentvelocity (1000) of X,y direction is calculated by sliding distance; 
    float Velocityx = Math.Abs (Mvelocitytracker.getxvelocity ()); float Velocityy = Math.Abs (mvelocitytracker.getyveloCity ()); Boolean dismiss = false; Item whether you want to slide out of the screen Boolean dismissright = false;//whether to the right delete//when the distance to drag item is greater than half of the item, item slides out of the screen if (Math.Abs delt 
      AX) &gt; Mviewwidth/2) {dismiss = true; 
       
      Dismissright = deltax &gt; 0; The speed at which the finger slides on the screen is within a range, and the item slides out of the screen} else if (mminflingvelocity &lt;= velocityx &amp;&amp; Velocityx &lt;= mmaxf 
      Lingvelocity &amp;&amp; Velocityy &lt; Velocityx) {dismiss = true; 
    Dismissright = mvelocitytracker.getxvelocity () &gt; 0; } if (dismiss) {viewpropertyanimator.animate (Mdownview). Translationx (dismissright? mviewwidth :-mviewwidth)//x moving distance in the direction of the axis. Alpha (0). Setduration (Manimationtime). Setlistener (New Animato Rlisteneradapter () {@Override public void Onanimationend (animator animation) {/ 
            /item after sliding out of the interface to perform delete Performdismiss (Mdownview, mdownposition); } 
          });   
      else {//slide item to start position Viewpropertyanimator.animate (Mdownview). Translationx (0). Alpha (1) 
    . Setduration (Manimationtime). Setlistener (NULL); 
      }//Remove speed detection if (mvelocitytracker!= null) {mvelocitytracker.recycle (); 
    Mvelocitytracker = null; 
  } mswiping = false; /** * After the item is deleted in this method, the other item scrolls up or down, and the position is recalled to Method Ondismiss () * @param dismissview * @p  Aram Dismissposition * * private void Performdismiss (final View dismissview, final int dismissposition) {final Viewgroup.layoutparams LP = Dismissview.getlayoutparams ()//Get item's layout parameter final int originalheight = dismissview.gethe 
    Ight ();//item height Valueanimator animator = valueanimator.ofint (originalheight, 0). Setduration (MAnimationTime); 
 
    Animator.start (); Animator.addlistener (New Animatorlisteneradapter () {@Override public void Onanimationend (animator animation ) {IF (ondismisscallback!= null) {Ondismisscallback.ondismiss (dismissposition); //This code is important because we have not removed item from ListView, we set the item height to 0//So we set the item back after the animation is finished Viewhelper.setal 
        PHA (Dismissview, 1f); 
        Viewhelper.settranslationx (Dismissview, 0); 
        Viewgroup.layoutparams LP = Dismissview.getlayoutparams (); 
        Lp.height = OriginalHeight; 
 
      DISMISSVIEW.SETLAYOUTPARAMS (LP); 
 
    } 
    }); Animator.addupdatelistener (New Valueanimator.animatorupdatelistener () {@Override public void onanimationupd Ate (Valueanimator valueanimator) {//The effect of this code is listview after deleting an item, the effect of the other item sliding upward lp.height = (Integer) valu 
        Eanimator.getanimatedvalue (); 
      DISMISSVIEW.SETLAYOUTPARAMS (LP); 
 
  } 
    }); /** * Delete Callback interface * * @author xiaanming * */public interface Ondismisscallback {public VO 
  ID ondismiss (int dismissposition); 

 } 
 
}

Seen Android use Scroller to achieve a gorgeous listview around delete item effects you will find that this custom Swipedismisslistview only rewrites the Ontouchevent () method, In fact, we rewrite this method to achieve the results we need
1. We first look at the finger presses the screen processing method Handleactiondown (), the method inside according to our finger pressed point according to Pointtoposition () method to obtain our click position, then use Getchildat () To get the view object of the item we pressed, and to add the finger to the speed check on the screen slide, this step is relatively simple

2. The next step is to slide the finger over the screen. Handleactionmove (), this method is slightly more complicated, we need to judge by the slide distance of the finger on the x axis and the slide distance of the Y axis listview The item's horizontal slide or listview sliding up and down, when satisfied Math.Abs (deltax) > Mslop && math.abs (DeltaY) < mslop this condition, We use a Boolean value mswiping to mark the item now sliding horizontally, and we need to handle the logic that the item slides with the slide of the finger, and we use Viewhelper to handle the sliding logic of the item, This class is based on the SDK version of the machine to determine whether to use the Android API or its own API in Nineoldandroids to make the view slide Nineoldandroids mainly uses camera (classes that can implement a variety of complex animation effects), we use Viewhelper Settranslationx () and Setalpha () to achieve the item slide and transparency gradient, In order to allow us to slide the item, ListView does not scroll up and down, we must return true to mask the ListView scrolling, here we need to be very familiar with the Android event distribution mechanism, here I do not explain, People do not understand the Internet to find relevant articles to see
Another problem is that when we slide the ListView item, it will be accompanied by the item's click event, which is not what we want, so when the item slides we need to cancel the ListView item Click event

3. When looking at the fingers to lift the processing method Handleactionup (), which needs to be based on the fingers of the sliding speed or item moving distance to determine whether the item is sliding out of the screen or sliding to the starting position, and to determine whether the item left or right slide out of the screen and so on logic, The specific logic can see the code, I believe we all understand.
I'm going to talk about the Viewpropertyanimator class, which is a better way to implement a view with multiple animations at the same time, Of course, we can also use Objectanimator to use Animatorset to implement multiple simultaneous animation effects on a view, for example, we can

Viewpropertyanimator.animate (Mdownview) 
    . Translationx (dismissright mviewwidth:-mviewwidth) Moving distance 
    in the direction of the//x axis . Alpha (0) 
    . Setduration (Manimationtime) 
    . Setlistener (New Animatorlisteneradapter () { 
      @Override 
        a Delete 
        Performdismiss (Mdownview, mdownposition) is performed after the interface is animator by the public void Onanimationend (animation) {//item); 
    }); 

Replace into

Animatorset set = new Animatorset (); 
      Set.playtogether (Objectanimator.offloat (Mdownview, "Translationx", Dismissright? Mviewwidth:-mViewWidth),  
              Objectanimator.offloat (Mdownview, "Alpha", 0)); 
      Set.setduration (Manimationtime). Start (); 
      Set.addlistener (New Animatorlisteneradapter () { 
            @Override public 
            void Onanimationend (animator animation) { 
              //item after sliding out of the interface 
              to perform delete Performdismiss (Mdownview, mdownposition); 
            } 
          ); 

The effect is the same, but Viewpropertyanimator is much higher in performance than using Objectanimator to implement multiple simultaneous animations, for example, if you want to use motion and transparency animations for view, With Viewpropertyanimator, we only need to invoke the invalidate () method to refresh the interface at some point in time, while using objectanimator, moving animations need to invoke invalidate (), Transparency animations also need to invoke the invalidate () method to use Animationset on performance lower than viewpropertyanimator, but sometimes we still need to use objectanimator, for example, at a certain time, We need to make the view bigger in the complexity of getting smaller and bigger, and that's when Objectanimator comes in handy, for example

Objectanimator.ofint (Mdownview, "ScaleX", 0, 0, m). Setduration (+). Start ()
Through the above a few steps we have achieved ListView the effect of the deletion of the item, but there is an effect, the item deleted, ListView the other item up or down slowly sliding effect, to achieve this is also very easy, is to dynamically set the height of the item, The item height becomes smaller, so that the other item will appear up or down the effect of squeezing!

4. Here we use the Valueanimator class, which is not an animation for view action, but an animation of a value that is used by default interpolator (interpolation) It's acceleratedecelerateinterpolator (start and end times slow, middle speed), for a very simple example, we use Valueanimator to change a value from 0 to 100 in 10 seconds. If you use Linearinterpolator (linear interpolation, constant change) in the first 2 seconds, this value becomes 20, but with Acceleratedecelerateinterpolator, which may be 15 or 13 in the first two seconds, So we set the listener to change the value of the valueanimator when the change is made Animatorupdatelistener knows how much the value of a certain time has changed to set the view's property (for example, size). So Valueanimator is an indirect animation of the view set.
Understand the use of valueanimator principle, we can be realistic above the animation effect, we use Valueanimator to the item's height into 0, set valueanimator change monitoring, We set the height of the item dynamically in the callback function Onanimationupdate (), and then add Animatorlistener listening to the state of the animation (for example, animation start, end, repetition, etc.), and the callback function at the end of the animation Onanimationend ( To delete the item's data, call notifydatasetchanged refresh ListView, and look at the following code

Viewhelper.setalpha (Dismissview, 1f); 
        Viewhelper.settranslationx (Dismissview, 0); 
        Viewgroup.layoutparams LP = Dismissview.getlayoutparams (); 
        Lp.height = OriginalHeight; 
        DISMISSVIEW.SETLAYOUTPARAMS (LP); 

We use animation just to move item out of the screen, and the item's height is set to 0, and the item's view is not removed from the ListView, and ListView can not directly remove the item, can only delete the data source, In the call to Notifydatasetchanged () refresh, so we need to return the item that just slid out of the screen height set to 0

Custom control code We're done, and we're going to use it, look at the layout code of the interface first.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"  
  xmlns:tools= "http:// Schemas.android.com/tools "  
  android:layout_width=" match_parent "  
  android:layout_height=" Match_parent " >  
  
  <com.example.swipedismisslistview.swipedismisslistview 
    android:id= "@+id/swipedismisslistview"  
    android:layout_width= "match_parent"  
    android:layout_height= "match_parent"  
    android:listselector= "@ Android:color/transparent " 
    android:cachecolorhint=" @android: Color/transparent ">  
  </ Com.example.swipedismisslistview.swipedismisslistview> 
  
</RelativeLayout>  

Very simply, a relativelayout wraps our custom ListView control, followed by the main interface code writing, as usual ListView use, but we need to set up ondismisscallback () monitoring,
Ondismiss () to delete the data for this location, refresh the ListView

Package Com.example.swipedismisslistview; 
Import java.util.ArrayList; 
 
Import java.util.List; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.widget.AdapterView; 
Import Android.widget.AdapterView.OnItemClickListener; 
Import Android.widget.ArrayAdapter; 
 
Import Android.widget.Toast; 
 
Import Com.example.swipedismisslistview.SwipeDismissListView.OnDismissCallback; 
  public class Swipeactivity extends activity {private Swipedismisslistview Swipedismisslistview; 
  Private arrayadapter&lt;string&gt; adapter; 
 
  Private list&lt;string&gt; datasourcelist = new arraylist&lt;string&gt; (); 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_swipe); 
  Init (); 
    private void Init () {Swipedismisslistview = (Swipedismisslistview) Findviewbyid (R.id.swipedismisslistview); for (int i = 0; i &lt; i++) {DataSOurcelist.add ("Slide Delete" + i); } adapter = new Arrayadapter&lt;string&gt; (this, Android. R.layout.simple_list_item_1, Android. 
     
    R.id.text1, datasourcelist); 
     
    Swipedismisslistview.setadapter (adapter); Swipedismisslistview.setondismisscallback (New Ondismisscallback () {@Override public void Ondismiss (  
      int dismissposition) {adapter.remove (Adapter.getitem (dismissposition)); 
     
     
    } 
    }); Swipedismisslistview.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick ( Adapterview&lt;?&gt; Parent, view view, int position, long id) {Toast.maketext (swipeactivity.this, ad 
      Apter.getitem (position), Toast.length_short). Show (); 
 
  } 
    }); 
 } 
 
}

All the code has been written, and the next step is to run the project to see if the specific effect is what we want.

Related Article

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.