"Android Custom Control" Android ListView Add side-Slip Delete

Source: Internet
Author: User
Tags gety

Added a cool item to the ListView with a side-by-side deletion, by using the padding (left and right) property in the item layout as a negative value to hide the deleted button out of the screen. Then through the custom ListView overrides the ontouchevent through the finger coordinate point computation to handle the event, realizes the Itemview scroll, achieves the sliding to appear deletes the menu, in this example only realizes the right-to-left sliding appears deletes the button, everybody can according to own demand, Refer to the custom ListView for event handling to make the left slide, and the right-hand slide appears on the menu, of course not just to delete. More flexible usage expect to discover.

First on the custom Listslideview code, where there are detailed comments, I will not nonsense! (The ListView refers to the previous project inside the event distribution processing judgment, specific reference to the great God's writing has been unable to elaborate, thanks to the original author of the same time, please forgive me, if you can contact the blogger, the reference source Plus)

Listslideview:

/** * Listslideview.java * 2015 PM 3:00:24 */package Com.example.slideviewtest;import Android.content.context;import Android.content.res.typedarray;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;/** * @note custom ListView, integrated from the system's ListView, The Ontouchenvent event distribution for list is intercepted (the most critical place, * is also implemented by this way to control the off-screen layout of the drag and drop) need to work with the layout file of the item to implement * @author blank * @time 3:00:24 *  @version V1.0 */public class Listslideview extends ListView {/** non-skid mode */public static int mode_forbid = 0;/** Slide Right-to-left menu mode */public static int mode_right = 1;/** current mode */private int mode = mode_forbid;/** Right menu length */private int rightlength = 0;/ * * Current sliding listview position */private int slideposition;/** * Finger press x coordinates */private int downy;/** * Finger press y coordinates */private int do wnx;/** * ListView Item */private View itemview;/** * Sliding class */private Scroller scroller;/** * Considered to be the most user-swipeSmall distance */private int mtouchslop;/** * Determine if you can swipe sideways */private boolean canmove = false;/** * Indicates whether to complete the slide-through */private boolean isslided = False;public Listslideview (context context) {This (context, null);} Public Listslideview (context context, AttributeSet Attrs) {This (context, attrs, 0); TypedArray a = context.obtainstyledattributes (attrs,r.styleable.slidemode); mode = A.getint (r.styleable.slidemode_ mode, 0);} Public Listslideview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); TypedArray a = context.obtainstyledattributes (attrs,r.styleable.slidemode); mode = A.getint (r.styleable.slidemode_ mode, 0); scroller = new Scroller (context); mtouchslop = Viewconfiguration.get (GetContext ()). Getscaledtouchslop ();  /** * Handle our 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");/* The default does not handle the event of the current view, that is, there is no */if menu (this.mode = = Mode_forbid) {return super.ontouchevent (EV);} The Slip state determines if (isslided) {scrollback (); return false;} Whether scrolling ends if (!scroller.isfinished ()) {return false;} DOWNX = (int) ev.getx ();d owny = (int) ev.gety (), slideposition = Pointtoposition (Downx, DownY);//Invalid positionif (Slideposi tion = = adapterview.invalid_position) {return super.ontouchevent (EV);} Itemview = Getchildat (Slideposition-getfirstvisibleposition ());/* The length of the menu on the right */if (This.mode = mode_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 = = mode_right) {/* swipe from right to left */c Anmove = true;} else {canmove = false;} /* Shield */motionevent CancelEvent = motionevent.obtain (EV) for the Onitemclicklistener event of the ListView when skidding; CancelEvent. Setaction (motionevent.action_cancel| (Ev.getactionindex () << motionevent.action_pointer_index_shift)); O Ntouchevent (CancelEvent);} if (canmove) {/* side slides, the ListView does not scroll up or down */requestdisallowintercepttouchevent (true);//the finger slide direction can be obtained by the difference of x-coordinate. This example can be flexibly modified according to their own needs (the left side of the menu, the right side of the menu, or left to all) int deltax = downx-lastx;if (DeltaX > 0 && this.mode = = mode_right) {/ * x-coordinate difference greater than 0 fingers swipe right */itemview.scrollto (deltax, 0);} else {itemview.scrollto (0, 0);} return true;} Case MotionEvent.ACTION_UP:System.out.println ("touch-->" + "up"); if (canmove) {canmove = False;scrollbydistancex () ;} break;} return super.ontouchevent (EV);} /** * Determines whether scrolling to the beginning or to the left or to the right, depending on the distance of the finger scrolling itemview */private void Scrollbydistancex () {/* The current mode does not allow sliding, then return directly to */if (This.mode = MO De_forbid) {return;} if (ITEMVIEW.GETSCROLLX () > 0 && this.mode = = mode_right) {/* swipe from right to left */if (ITEMVIEW.GETSCROLLX () >= Rightleng TH/2) {scrollleft ();} else {//rollback to original location scrollback ();}} else {//Roll back to original location scrollback ();}} /** * Swipe left */private void ScrollLeft () {Isslided = true;final int delta = (RIGHTLENGTH-ITEMVIEW.GETSCROLLX ());//Call the Startscroll method to set some scrolling parameters that we have in the Computescroll () Method calls Scrollto to scroll itemscroller.startscroll (ITEMVIEW.GETSCROLLX (), 0, Delta, 0,math.abs (Delta));p ostinvalidate (); Refresh itemview}/** * Slide-off menu restore */private void Scrollback () {isslided = False;scroller.startscroll (Itemview.getscrollx (), 0,- ITEMVIEW.GETSCROLLX (), 0, Math.Abs (ITEMVIEW.GETSCROLLX ()));p ostinvalidate (); Refresh Itemview} @Overridepublic void Computescroll () {//Call Startscroll when Scroller.computescrolloffset () returns TRUE,IF ( Scroller.computescrolloffset ()) {//Let ListView item Scroll Itemview.scrollto (SCROLLER.GETCURRX () according to the current scroll offset, Scroller.getcurry ());p ostinvalidate ();}} /** * Restore */public void Slideback () {this.scrollback ();}}

Custom control properties that need to be skidded are added in order to be compatible with the previous ListView

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Slidemode" >        <attr name= "mode" >            <enum name= "forbid" value= "0" ></enum>            <enum name= "right" value= "1" ></enum>        </attr>    </declare-styleable></resources>

0 for non-slip, 1 for the right side, can be added to the left slide according to your needs

Layout of Itemview:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @android: Co Lor/white "android:gravity=" center_vertical "android:orientation=" horizontal "android:paddingbottom=" 10DP "and roid:paddingright= " -90DP" android:paddingtop= "10DP" android:weightsum= "1" > <linearlayout android:la Yout_width= "0DP" android:layout_height= "96DP" android:layout_weight= "0.35" android:orientation= "Verti            Cal "> <imageview android:id=" @+id/imgicon "android:layout_width=" Fill_parent " android:layout_height= "0DP" android:layout_weight= "1" android:scaletype= "Fitxy" Androi d:src= "@drawable/images"/> <textview android:id= "@+id/tvprice" android:layout_width= "f Ill_parent "Android:layout_height= "Wrap_content" android:gravity= "Center_horizontal" android:text= "$128.5"/> </Lin earlayout> <linearlayout android:layout_width= "0DP" android:layout_height= "96DP" Android:lay out_weight= "0.65" android:orientation= "vertical" android:padding= "5DP" > <textview A Ndroid:id= "@+id/tvname" android:layout_width= "fill_parent" android:layout_height= "0DP" an droid:layout_weight= "1" android:text= "HP 14-P010NR touchscreen Slatebook, Nividia TE" Android:tex tstyle= "Bold"/> <ratingbar android:id= "@+id/ratingbar" style= "? Android:attr/ratingbars Tylesmall "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Andro id:numstars= "5"/> </LinearLayout> <textview android:id= "@+id/tvdelete" Android:layout_wid Th= "90DP" Android: layout_height= "96DP" android:layout_centerinparent= "true" android:layout_marginright= " -5DP" Android: Background= "@android: Color/holo_red_light" android:gravity= "center" android:text= "Delete" Android:tex Tcolor= "@android: Color/white" android:textsize= "15SP"/></linearlayout>

In order to fit the adapter of the Listslideview:

Package Com.example.slideviewtest;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.baseadapter;import android.widget.textview;/** * @author Blank * @time pm 4:01:07 * @version V1.0 */public C Lass Slideviewadapter extends Baseadapter {private Context mcontext;private layoutinflater layoutinflr;private int itemtype = 1;private onremovelistener mremovelistener;public int Getitemtype () {return itemtype;} public void Setitemtype (int itemtype) {this.itemtype = itemtype;} Public Slideviewadapter (Context context) {This.mcontext = CONTEXT;THIS.LAYOUTINFLR = (layoutinflater) Context.getsystemservice (Context.layout_inflater_service);} public void Setremovelistener (Onremovelistener removelistener) {this.mremovelistener = RemoveListener;} Class Viewlayout {Private TextView mdelete;//hidden side-slip Delete button} @Overridepublic int GetCount () {//TODO auto-generated method stub return 10;}@Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn null;} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic View GetView (final int position, view Convertview, ViewGroup parent) {viewlayout icom_view;if (Convertvie W = = null) {Icom_view = new viewlayout (); Convertview = Layoutinflr.inflate (r.layout.item_product_listview,null); icom_ View.mdelete = (TextView) Convertview.findviewbyid (r.id.tvdelete); Convertview.settag (Icom_view);} else {Icom_view = (viewlayout) Convertview.gettag ();} Icom_view.mDelete.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (view v) {//TODO Auto-generated method Stubif (mremovelistener!=null) {mremovelistener.onremoveitem (position);}}); return Convertview;} public interface Onremovelistener {void onremoveitem (int position);}}

The demo did not fill the data, the deleted event callback out!

Here are 2 photos:











Source: http://download.csdn.net/detail/q849340003/8959897



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

"Android Custom Control" Android ListView Add side-Slip Delete

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.