This article uses the Scroller class described in the previous article to accomplish a more common effect-sliding delete effects. The code is as follows:
Simpleswipelistview:
Package Cn.edu.chd.simpleswipelistview;import Android.content.context;import Android.util.attributeset;import Android.util.log;import Android.view.motionevent;import Android.view.view;import android.view.ViewConfiguration; Import Android.view.windowmanager;import Android.widget.abslistview;import Android.widget.listview;import android.widget.scroller;/** * @author ROWANDJJ * * Sliding Delete Example */public class Simpleswipelistview extends Listview{private stat IC final String TAG = "Simpleswipelistview";p rivate static final Boolean DEBUG = true;private Scroller Mscroller = NULL;PR ivate int mtouchslop;/** * screen width */private int mscreenwidth;private View targetview;/** * Current item position */private int position; /** * Finger pressed position */private int downx,downy;/** * Can delete item */private boolean canremove = True;private Boolean isswipe;/** * I Tem deleted callback Event */private Onitemremovedlistener Mlistener;public interface onitemremovedlistener{public void RemoveItem ( int position);} public void Setonitemremovedlistener (onitemremovedlistEner listener) {This.mlistener = listener;} Public Simpleswipelistview (Context context) {This (context, null);} Public Simpleswipelistview (context context, AttributeSet Attrs) {This (context, attrs, 0);} Public Simpleswipelistview (context context, AttributeSet Attrs,int defstyleattr) {Super (context, attrs, defstyleattr); Init (context);} private void init (context context) {Mtouchslop = Viewconfiguration.get (GetContext ()). Getscaledtouchslop (); Mscreenwidth = ((WindowManager) Context.getsystemservice (Context.window_service)). Getdefaultdisplay (). GetWidth (); Mscroller = new Scroller (context);} @Overridepublic boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:if (! Mscroller.isfinished ()) return super.ontouchevent (EV);d ownx = (int) ev.getx ();d owny = (int) ev.gety ();// Get positionposition = Pointtoposition (Downx, DownY) according to coordinates; if (position = = Abslistview.invalid_position) return Super.ontouchevent (EV);//view object represented by position TargetView = Getchildat (Position-getfirstvisiblepoSition ()); break;case MotionEvent.ACTION_MOVE:int x = (int) ev.getx (); int y = (int) ev.gety (); if (Math.Abs (X-DOWNX) > Mtouchslop&&math.abs (y-downy) <mtouchslop) {int deltax = Downx-x;downx = X;downy = Y;targetView.scrollBy ( deltax,0); isswipe = true;} if (isswipe)//Disable ListView scrolling return true;break;case MotionEvent.ACTION_UP:scrollByOffset (); isswipe = False;break;} return super.ontouchevent (EV);} /** * Determines whether to scroll left or right according to offset */private void Scrollbyoffset () {int scrollx = TARGETVIEW.GETSCROLLX ();//Current offset if (Scrollx > MSCREENWIDTH/3)//should roll to the left {scrolltoleft (SCROLLX);} else if (Scrollx <-MSCREENWIDTH/3)//should roll right {scrolltoright (SCROLLX);} else//Roll back to Origin {Scrolltoorigin (SCROLLX);}} private void Scrolltoorigin (int scrollx) {mscroller.startscroll (Scrollx,0,-scrollx,0,math.abs (SCROLLX)); Postinvalidate (); canremove = false;} /** * Scroll right */private void scrolltoright (int scrollx) {int deltax = Mscreenwidth+scrollx;mscroller.startscroll (ScrollX, 0, -deltax, 0, Math.Abs (deltax)); invalidate (); canremove = true;} /** * Scroll Left */private void scrolltoleft (int scrollx) {int deltax = Mscreenwidth-scrollx;mscroller.startscroll (scrollx, 0, DeltaX, 0, Mat H.abs (DeltaX)); invalidate (); canremove = true;} @Overridepublic void Computescroll () {if (Mscroller! = null) {if (Mscroller.computescrolloffset ()) {int Currx = Mscroller.getcurrx (); int currY = Mscroller.getcurry (); Targetview.scrollto (Currx,curry);p ostinvalidate (); if ( Mscroller.isfinished ()) {targetview.scrollto (0, 0), if (Canremove) {if (Mlistener = = null) throw new RuntimeException (" You must call Setonremoveitemlistener to set a listener "), if (DEBUG) log.d (TAG," position: "+position);// Delete Itemmlistener.removeitem (position); canremove = false;}}}}}
Layout: Activity_main.xml
< 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:backg Round= "#ededed" tools:context= "cn.edu.chd.simpleswipelistview.MainActivity" > < Cn.edu.chd.simpleswipelistview.SimpleSwipeListView android:id= "@+id/lv" android:layout_width= "Match_parent" android:layout_margintop= "2DP" android:layout_marginbottom= "2DP" android:layout_height= "wrap_content "Android:listselector=" @android: Color/transparent "android:cachecolorhint=" @android: Color/transparent " Android:divider= "@null" android:dividerheight= "2DP" ></cn.edu.chd.simpleswipelistview.simpleswipeli Stview> </relativelayout>
Item.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:paddingleft=" 3DP "an Droid:descendantfocusability= "beforedescendants" android:paddingright= "3DP" > <!--scrolling is the following content--<linea Rlayout android:layout_width= "match_parent" android:layout_height= "55DP" android:background= "@drawabl E/card_background_selector "android:gravity=" Center_vertical|left "android:descendantfocusability=" AfterDesc Endants "android:orientation=" vertical "> <textview android:id=" @+id/tv "Android : layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_marginleft= "10DP" Android:textcolor= "@android: Color/black" android:textsize= "18sp"/> </linearlayout></f Ramelayout>
Main interface code:
Package Cn.edu.chd.simpleswipelistview;import Java.util.arraylist;import Java.util.list;import Android.app.activity;import Android.os.bundle;import Android.widget.arrayadapter;import Cn.edu.chd.simpleswipelistview.simpleswipelistview.onitemremovedlistener;public class MainActivity extends Activity{private Simpleswipelistview Mlistview = null;private arrayadapter<string> mAdapter = null;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Mlistview = (Simpleswipelistview) Findviewbyid (r.id.lv); final list<string> data = new Arraylist<string> (); for (int i = 0; i <, i++) {Data.add ("This is Text num" +i);} Madapter = new Arrayadapter<> (This,r.layout.item, r.id.tv, data); Mlistview.setadapter (Madapter); Mlistview.setonitemremovedlistener (New Onitemremovedlistener () {@Overridepublic void RemoveItem (int position) {// Call notifydatasetchanged is not used here because the Remove method internally calls Madapter.remove (Data.get (position));}});}}
The effect screenshot is inconvenient, let's see for yourselves.
I believe that you combined with the previous article introduced scroller Understanding code should be very easy. The key points to note are the following: 1. How to find the View object based on coordinates. (use of Pointtoposition and Getchildat methods) 2.Scroller, in particular Scrollto, Scrollby, and Computescroll methods. 3. Be aware that if you want to scroll through a view, you should call the Scrollto, Scrollby method of its parent view. 4. Handle the sliding conflict, avoid the ListView scrolling when you remove the slide horizontally.
GitHub Source: Https://github.com/Rowandjj/SimpleSwipeListView
"Android Notes" sliding Delete example