Android Implementation user list information swipe delete function and select Delete function

Source: Internet
Author: User

In the project development process, it is often necessary to delete the information of the user list. There are two types of deletions that are commonly used in Android, one of which is a similar swipe to delete button, and one that is selected by a checkbox and then deleted by a button. The original example integrates the above two modes of operation to achieve the effect of user list deletion.

Design idea: In the adapter class myadapter a slide Delete button to show or hide the map, a map for checkbox selection and an interface Contentsdeletelistener for data interaction with MAINACITIVYT, The interface also contains two methods, the contentsdeleteselect (int position, Boolean isChecked) method is used to add or remove selected or canceled content from the selected list, contentdelete (int Position) is used to delete the column item at the specified position in the list. The effect of sliding is mainly through when the sliding distance is greater than 40 o'clock, the slide Delete button is displayed, then all other settings are not visible when the delete operation is performed, and the checkbox is set unchecked.

I. Code implementation EFFECTS


Two. Code implementation

1. Main interface Layout Activity_main.xml

<span style= "FONT-SIZE:18PX;" ><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 "    >    <button    android:id= "@+id/my_delete_btn"    android:layout_width= "Match_parent    " android:layout_height= "Wrap_content"    android:layout_alignparentbottom= "true"    android:text= "@string/ Delete "    />    <listview        android:id=" @+id/my_lv "        android:layout_width=" Match_parent "        android:layout_height= "match_parent"        android:layout_alignparenttop= "true"        Android:layout_above = "@id/my_delete_btn"       android:contentdescription= "@string/member_list"/></relativelayout></ Span>
the main interface layout is simple, just a delete button and a ListView that holds user information

2. User Item Layout Activity_main_list_view.xml

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:id=" @+id/my_rl "android:layout_width=" match_parent "android:layout_height=" 200DP "> &L T CheckBox android:id= "@+id/my_select_cb" android:layout_width= "wrap_content" android:layout_height= "WR Ap_content "android:layout_alignparentleft=" true "android:layout_centervertical=" true "android:layout    _marginleft= "10DP" android:background= "@drawable/my_list_checkbox_selector" android:button= "@null"/> <textview android:id= "@+id/my_content_tv" android:layout_width= "Wrap_content" Android:layout_heigh t= "60DP" android:layout_centerinparent= "true" android:layout_marginleft= "20DP" android:layout_toright of= "@id/MY_SELECT_CB" android:gravity= "center" android:text= "@string/delete"/> <textview ANdroid:id= "@+id/my_delete_tv" android:layout_width= "80DP" android:layout_height= "Wrap_content" Androi        D:layout_alignparentright= "true" android:layout_centerinparent= "true" android:layout_marginleft= "5DP" Android:clickable= "true" android:drawableleft= "@drawable/del_icon_normal" android:gravity= "center" a ndroid:paddingleft= "10DP" android:paddingright= "10DP" android:text= "@string/delete" Android:visibilit Y= "Gone"/></relativelayout></span>
The layout contains a selected checkbox that shows the contents of the TextView and a sliding textview to implement the deletion

3. Slide Effect Anim_right_left.xml

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><set xmlns:android= "Http://schemas.android.com/apk/res/android ">    <translate android:duration=" "Android:fromxdelta=" "        android:fromydelta=" 0 "        android:toxdelta= "0"        android:toydelta= "0"/></set></span>

4.CheckBox Selector my_list_checekbox_selector.xml

<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">     <item android:drawable=" @drawable/my_list_check_box_bg_check "android:state_checked=" true " ></item>      <item android:drawable= "@drawable/my_list_check_box_bg_check" android:state_selected= " True "></item>      <item android:drawable=" @drawable/my_list_check_box_bg_check "Android:state_ Pressed= "true" ></item>      <item android:drawable= "@drawable/my_list__check_box_bg" ></item >  </selector></span>

5 . User List Adapter Myadapter.java

<span style= "FONT-SIZE:18PX;" >package Com.example.slideandselectdeletedemo;import Java.util.hashmap;import Java.util.List;import Java.util.map;import Android.annotation.suppresslint;import Android.content.context;import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.view.ontouchlistener;import Android.view.animation.animation;import Android.view.animation.animationutils;import Android.view.ViewGroup; Import Android.widget.baseadapter;import Android.widget.checkbox;import Android.widget.compoundbutton;import Android.widget.compoundbutton.oncheckedchangelistener;import Android.widget.relativelayout;import Android.widget.textview;import COM.EXAMPLE.SLIDEDELETEANDSELECTDEMO.R; @SuppressLint ("Usesparsearrays") public Class Myadapter extends Baseadapter {private Layoutinflater minflater;private list<string> mcontentslist;private Context mcontext;private Contentsdeletelistener mcontentsdeletelistener;//Set Slide Delete button to show private Map<integer, integer> Visibledeletetv;//checkbox Select and no private map<  Integer, boolean> selectcb;//after sliding the x coordinate point private int mlastx = 0;//private int mlasty = 0;public Myadapter (Context mcontext, List<string> Mcontentslist,contentsdeletelistener mcontentsdeletelistener) {this.mContext = MContext; This.mcontentslist = Mcontentslist;this.mcontentsdeletelistener = Mcontentsdeletelistener;this.minflater = ( Layoutinflater) Mcontext.getsystemservice (context.layout_inflater_service); Visibledeletetv = new HashMap< Integer, integer> (); SELECTCB = new Hashmap<integer, boolean> ();//update interface, record as unchecked and slide Delete button not visible for (int i = 0; i < Mcontentslist.size (); i++) {visibledeletetv.put (I, View.gone); Selectcb.put (I, False);}} public void Updateview (list<string> mcontentslist) {this.mcontentslist = mcontentslist; This.notifydatasetchanged ();} @Overridepublic int GetCount () {return mcontentslist.size ();} @Overridepublic Object getItem (int position) {RetuRN Mcontentslist.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic View GetView (final int position, view Convertview, ViewGroup parent) {final Holderview holderview;if (CONV Ertview = = null) {Holderview = new Holderview (); Convertview = Minflater.inflate (r.layout.activity_main_list_view,null) ; HOLDERVIEW.LISTSELECTCB = (CheckBox) Convertview.findviewbyid (R.ID.MY_SELECT_CB); Holderview.listcontenttv = ( TextView) Convertview.findviewbyid (R.ID.MY_CONTENT_TV); Holderview.listdeletetv = (TextView) Convertview.findviewbyid (R.ID.MY_DELETE_TV); Holderview.listrl = (relativelayout) Convertview.findviewbyid (R.id.my _RL); Convertview.settag (Holderview);} else {Holderview = (Holderview) convertview.gettag (); if (holderView.listSelectCb.isChecked ()) { HolderView.listSelectCb.setChecked (FALSE);}} Display Content HolderView.listContentTv.setText (mcontentslist.get (position)); if (Visibledeletetv! = null) { HolderView.listDeleteTv.setVisibility (Visibledeletetv.get (position));} if (SELECTCB = null) {holderView.listSelectCb.setChecked (Selectcb.get (position)); Mcontentsdeletelistener.contentsdeleteselect (Position,selectcb.get (position));} Handle Selection Event HolderView.listRl.setOnClickListener (new Onclicklistener () {@Overridepublic void OnClick (View v) {if ( Visibledeletetv.containsvalue (view.visible)) {//visible, click again setting is not visible, no for (int i = 0; i < GetCount (); i++) { Visibledeletetv.put (i, View.gone); Selectcb.put (I, false); Mcontentsdeletelistener.contentsdeleteselect (I, false);} Notifydatasetchanged ();} else {Boolean isChecked = holderView.listSelectCb.isChecked ()? false:true;holderview.listselectcb.setchecked ( isChecked); Mcontentsdeletelistener.contentsdeleteselect (position, isChecked);}}); HolderView.listSelectCb.setOnCheckedChangeListener (New Oncheckedchangelistener () {@Overridepublic void OnCheckedChanged (Compoundbutton Buttonview,boolean isChecked) {Mcontentsdeletelistener.contentsdeleteselect ( position,ischecked);}); HolderView.listSelectCb.setOnClickListener (New OnclicklistenER () {@Overridepublic void OnClick (View v) {if (Visibledeletetv.containsvalue (view.visible)) {for (int i = 0; i < Getco UNT (); i++) {visibledeletetv.put (I, View.gone); Selectcb.put (I, false); Mcontentsdeletelistener.contentsdeleteselect (I, FALSE);} Notifydatasetchanged ();}}); Convertview.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent event) { Final Animation alpha = animationutils.loadanimation (mcontext,r.anim.anim_right_left); int x = (int) event.getx ();//int  y = (int) event.gety ();//LOG.D (TAG, "x=" + x + "y=" + y);//Press Downif (event.getaction () = = Motionevent.action_down) {Alpha.cancel ();} else if (event.getaction () = = Motionevent.action_move) {alpha.cancel (); int deltax = Mlastx-x;//int DeltaY = mlasty-y;/ /LOG.D (TAG, "deltax=" + DeltaX + ", deltay=" + DeltaY); if (DeltaX > 40) {//when the sliding distance is greater than 40 o'clock, the delete key for the position is displayed for (int i = 0; i < GetCount (); i++) {visibledeletetv.put (I, View.gone); Selectcb.put (I, false); mcontentsdeletelistener.contentSdeleteselect (I, False), if (i = = position) {Visibledeletetv.put (position, view.visible); Selectcb.put (I, true); Mcontentsdeletelistener.contentsdeleteselect (I, true); if (visibledeletetv.get (position) = = view.visible) { HolderView.listDeleteTv.startAnimation (alpha);}}} Notifydatasetchanged ();} return true;} else {//Otheralpha.cancel ();} MLASTX = X;//mlasty = Y;return false;}}); HolderView.listDeleteTv.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View v) {///LOG.D (TAG, "onclick:position=" + position); Mcontentslist.remove (position); Mcontentsdeletelistener.contentdelete (position); for (int i = 0; i < mcontentslist.size (); i++) {Visibledeletetv.put (I, View.gone); Selectcb.put (I, false); Mcontentsdele Telistener.contentsdeleteselect (I, false);} Notifydatasetchanged ();}}); return Convertview;} public class Holderview {public TextView Listcontenttv, listdeletetv;public CheckBox listselectcb;public relativelayout Listrl;} public void Setcontentsdeletelistener (ContentsdeletelistenEr mcontentsdeletelistener) {this.mcontentsdeletelistener = Mcontentsdeletelistener;}  /** * Interface for deleting content * * @author Liangming.deng * */public interface Contentsdeletelistener {/** * Select and deselect the specified location according to ischecked * @param position * @param isChecked */public void contentsdeleteselect (int position, Boolean isChecked);/** * Delete specified location contents * @ param position */public void contentdelete (int position);} public void Setvisibledeletetv (Map<integer, integer> visibledeletetv) {This.visibledeletetv = VisibleDeleteTv;} public void SETSELECTCB (Map<integer, boolean> selectcb) {THIS.SELECTCB = SELECTCB;}} </span>

5 . Main interface Code Mainactivity.java

<span style= "FONT-SIZE:18PX;" >package Com.example.slideandselectdeletedemo;import Java.util.arraylist;import Java.util.Collections;import Java.util.list;import Android.app.activity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.listview;import Com.example.slideandselectdeletedemo.myadapter.contentsdeletelistener;import Com.example.slidedeleteandselectdemo.r;public class Mainactivity extends Activity implements Contentsdeletelistener, Onclicklistener{private ListView mylv;private Button mydeletebtn;private myadapter myadapter;private String[] Mycontentsarray;private list<string> mycontentslist = new arraylist<string> ();p rivate List<String> Myselectedlist = new arraylist<string> (); @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); FindByID (); mycontentsarray = This.getresources (). Getstringarray (r.array.my_contents); if (Mycontentsarray! = null) {Collections.addall (mycontentslist, Mycontentsarray);} Myadapter = new Myadapter (this,mycontentslist,this); Mylv.setadapter (Myadapter);} private void FindByID () {mylv = (ListView) This.findviewbyid (R.ID.MY_LV); mydeletebtn = (Button) This.findviewbyid ( R.ID.MY_DELETE_BTN); Mydeletebtn.setonclicklistener (this);} @Overridepublic void Onresume () {Super.onresume ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up button so long//as you specify a parent activity in and RoidManifest.xml.int id = item.getitemid (); if (id = = r.id.action_settings) {return true;} Return SUPER.ONOPTIONSITEMSELECTED (item);} /* * Add or remove data from the selected list * (non-javadoc) * According to ischecked * @see Com.example.slideandselectdeletedemo.myadapter.contentsdeletelistener#contentsdeleteselect (int, Boolean) */@ overridepublic void contentsdeleteselect (int position,boolean isChecked) {if (isChecked) {Myselectedlist.add ( Mycontentslist.get (position));} Else{myselectedlist.remove (Mycontentslist.get (position));}} /* * Delete data at the specified location * (non-javadoc) * @see com.example.slideandselectdeletedemo.myadapter.contentsdeletelistener# Contentdelete (int) */@Overridepublic void contentdelete (int position) {//TODO auto-generated method Stubmycontentslist.remove (position);} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.ID.MY_DELETE_BTN: Mycontentslist.removeall (myselectedlist); Myadapter.updateview (mycontentslist); break;}} </span>

Analysis: Where myselectedlist is primarily used to store the list information checked by the checkbox. Easy Delete button to delete all selected.

The main section above gives a comment.

Source Address: http://download.csdn.net/detail/a123demi/7751141





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.