Swipe to delete the ListView item

Source: Internet
Author: User
Tags gety

Reprint Please specify source: http://blog.csdn.net/forwardyzk/article/details/42643865

When playing QQ, we will see this effect, you can swipe to delete the message, the following simulation of this effect.



1. Create a class Listviewcompat, inherit the ListView.

Overrides its Ontouchevent event.

@Overridepublic boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.action_down: { int x = (int) event.getx (), int y = (int) event.gety (), int position = Pointtoposition (x, y); if (Position! = Invalid_positio N) {//Gets the item content, gets the view object displayed by item, which is slideviewmessageitem data = (Messageitem) getitematposition (position); Mfocuseditemview = Data.getslideview ();}} Default:break;} if (Mfocuseditemview! = null) {mfocuseditemview.onrequiretouchevent (event);} Return Super.ontouchevent (event);}

Pointtoposition gets the location of the clicked item position, and then gets the information about the item in the adapter by getitematposition (position). View the source of the Getitematposition

/**     * Gets The data associated with the specified position in the list.     *     * @param position which data to get     * @return The data associated and the specified position in the list */     Public    Object getitematposition (int position) {        T adapter = Getadapter ();        Return (adapter = = NULL | | Position < 0)? Null:adapter.getItem (position);    }

The call is GetItem (). So when defining the adapter, remember to override the GetItem (int position) method

Mfocuseditemview.onrequiretouchevent (event) Action Ontouchevent () event for item

2.MessageItem is the information object to display the item.

/** *  * Item display information class, contains delete button, message to display *  */public class Messageitem {private String tv_content;private Slideview Slideview;public String gettv_content () {return tv_content;} public void Settv_content (String tv_content) {this.tv_content = tv_content;} Public Slideview Getslideview () {return slideview;} public void Setslideview (Slideview slideview) {this.slideview = Slideview;}}
Tv_content: Is the contents of the item display information

Slideview Slideview: Is the return value of item's View,getview () in the adapter, and the ListView item shows the Slideview.


3. Let's look at the defined adapter

Public View GetView (final int position, View Convertview, ViewGroup parent) {Viewholder holder; Slideview Slideview = (slideview) convertview;if (Slideview = null) {View Itemview = view.inflate (mcontext,r.layout.item _listview_delete, NULL);//Set the item display to the Item object Slideview = new Slideview (mcontext); Slideview.setcontentview ( Itemview); holder = new Viewholder (Slideview); Slideview.setonslidelistener (slideadapter.this); Slideview.settag ( Holder);} else {holder = (Viewholder) Slideview.gettag ();} Messageitem item = mmessageitems.get (position); Item.setslideview (Slideview); Item.getslideview (). Shrink (); Holder.tv_content.setText (Item.gettv_content ()); Holder.deleteHolder.setOnClickListener (new Onclicklistener () {@ overridepublic void OnClick (View v) {if (Deleteitemlistener! = null) {Deleteitemlistener.deleteitem (V, Position);}}); return Slideview;}


The default is shown at the origin point Item.getslideview (). Shrink ();

Item.setslideview (Slideview); Sets the current item object to the property of the item information object, in order to invoke its item's Ontouchevent () event conveniently in the ListView ontouchevent.

Set Slide monitoring: Slideview.setonslidelistener (Slideadapter.this);


Will convert the Convertview to Slideview. Adds the contents of the directly displayed item to the content view of the Slideview object

View Itemview = view.inflate (mcontext,r.layout.item_listview_delete, NULL);

Slideview.setcontentview (Itemview);


Item_listview_delete.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=" 58DP    " android:background= "@drawable/delete_list_item_bg"    android:descendantfocusability= "Blocksdescendants    " Android:gravity= "center_vertical"    android:paddingbottom= "5DP"    android:paddingleft= "10DP"    android: paddingright= "10DP"    android:paddingtop= "5DP" >    <textview        android:id= "@+id/tv_content"        android:layout_width= "match_parent"        android:layout_height= "wrap_content"        android:gravity= " Center "        android:textcolor=" @android: Color/black "        android:textsize=" 25SP "/></relativelayout>

Slideview loading a layout file

Activity_listview_delete_slide_view_merge.xml

<merge xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" Android: layout_height= "Match_parent" > <linearlayout android:id= "@+id/view_content" Android:layout_width= "M Atch_parent "android:layout_height=" match_parent "android:orientation=" Horizontal "> </LinearLayout > <relativelayout android:id= "@+id/holder" android:layout_width= "120DP" Android:layout_heigh t= "Match_parent" android:clickable= "true" android:background= "@drawable/delete_holder_bg" > <tex TView android:id= "@+id/delete" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:drawableleft= "@drawable/delete_icon_normal" android:layout_centerinparent= "tr UE "android:gravity=" center "android:textcolor=" @android: Color/white "android:text=" Delete "/ > </relativelayout></merge> 
In fact, the content of the display item is added to the layout loaded in Slideview, and the ID is in the view_content first layout.

View.inflate (Mcontext,r.layout.activity_listview_delete_slide_view_merge, this); mviewcontent = (LinearLayout) Findviewbyid (r.id.view_content);

public void Setcontentview (view view) {Mviewcontent.addview (view);}


This will completely display the entire item (including the Delete button) to the item.

4. We want to monitor the item's swipe event

public void Onrequiretouchevent (Motionevent event) {int x = (int) event.getx (); int y = (int) event.gety (); int scrollx = GE TSCROLLX (); switch (Event.getaction ()) {case Motionevent.action_down: {if (!mscroller.isfinished ()) { Mscroller.abortanimation ();} if (Monslidelistener! = null) {monslidelistener.onslide (this,onslidelistener.slide_status_start_scroll);} break;} Case Motionevent.action_move: {int deltax = X-mlastx;int DeltaY = y-mlasty;if (Math.Abs (DeltaX) < Math.Abs (DeltaY) * TAN) {break;} int newscrollx = Scrollx-deltax;if (deltax! = 0) {if (Newscrollx < 0) {newscrollx = 0;} else if (Newscrollx > Mhol Derwidth) {newscrollx = Mholderwidth;} This.scrollto (NEWSCROLLX, 0);} break;} Case MOTIONEVENT.ACTION_UP: {int newscrollx = 0;if (scrollx-mholderwidth * 0.75 > 0) {newscrollx = Mholderwidth;} This.smoothscrollto (NEWSCROLLX, 0), if (monslidelistener! = null) {monslidelistener.onslide (This,newscrollx = = 0?) OnSlideListener.SLIDE_STATUS_OFF:OnSlideListener.SLIDE_STATUS_ON);} BreaK;} Default:break;} Mlastx = X;mlasty = y;}

in Motionevent.action_down, when you click Down, you will call the swipe listener event Onslidelistener, execute Onslide,

Monslidelistener.onslide (This,onslidelistener.slide_status_start_scroll)

However, this listener is handled in the adapter

public void Onslide (view view, int status) {if (Mlastslideviewwithstatuson! = null&& Mlastslideviewwithstatuson!) = view) {Mlastslideviewwithstatuson.shrink ();} if (status = = slide_status_on) {Mlastslideviewwithstatuson = (Slideview) view;}}

is to put the previous one without going back to the origin, so that it slides to the origin, and keeps clicking the ListView when its item all goes back to the origin.

Motionevent.action_move: Slide the distance to move the Item,this.scrollto (newscrollx, 0); just move horizontally,

if (Newscrollx < 0) {newscrollx = 0;} else if (Newscrollx > Mholderwidth) {newscrollx = Mholderwidth;}

Limits the range of the slide.

MOTIONEVENT.ACTION_UP: When the value is left, it will be adjusted to show the Delete button depending on the position of the slide. When the distance is greater than 3/4 of the width of the delete button, the Delete button is displayed, otherwise the item returns to the original point. This.smoothscrollto (NEWSCROLLX, 0);

At the same time to put monslidelistener.onslide (This,newscrollx = = 0?) Onslidelistener.slide_status_off
: onslidelistener.slide_status_on)

The current item object is recorded in the adapter so that when the next item is clicked, the current item is moved to the origin.

/** * Causes item to return to the dot position */public void shrink () {if (GETSCROLLX ()! = 0) {this.smoothscrollto (0, 0);}}

5. Set a deleted listener event in the adapter

Private Deleteitemlistener deleteitemlistener;/** * @param deleteitemlistener *            settings Delete Item listener event */public void Setdeleteitemlistener (Deleteitemlistener deleteitemlistener) {this.deleteitemlistener = DeleteItemListener;}

Holder.deleteHolder.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View v) {if ( Deleteitemlistener! = null) {Deleteitemlistener.deleteitem (V, Position);}});

6. Steps to use

Layout file

<com.example.view.listviewcompat        android:id= "@+id/list"        android:layout_width= "Match_parent        " android:layout_height= "Match_parent"        android:background= "#fff4f7f9"        android:cachecolorhint= "#00000000"        android:divider= "#dddbdb"        android:dividerheight= "1.0px"        android:drawselectorontop= "false"        Android:listselector= "@android: color/transparent"        android:scrollbars= "None"/>

public void Initview () {Mlistview = (Listviewcompat) Findviewbyid (r.id.list), for (int i = 0; i <; i++) {Messageitem item = new Messageitem (); Item.settv_content ("I am  the first" + i + "item"); Mmessageitems.add (item);} Create Adapter Object adapter = new Slideadapter (deletelistviewmainactivity.this,mmessageitems);// Delete Listener Adapter.setdeleteitemlistener (new Deleteitemlistener () {@Overridepublic void DeleteItem (view view, int position) { Mmessageitems.remove (position); adapter.notifydatasetchanged (); Toast.maketext (Getapplicationcontext (), "deleted"  + position + "item", 0). Show ();}); /set Adapter Mlistview.setadapter (adapter);//Click the Item event Mlistview.setonitemclicklistener (new Onitemclicklistener () {@ overridepublic void Onitemclick (adapterview<?> parent, View view,int position, long id) {Toast.maketext ( Getapplicationcontext (), "clicked =" + position, 0). Show ();}});

source Download: http://download.csdn.net/detail/forwardyzk/8353961

:



Swipe to delete the ListView 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.