Android implementation ListView left and right sliding delete and edit _android

Source: Internet
Author: User
Tags abs gety

Sometimes, in order to achieve the requirements of the project, complete the design of the user interaction experience, do not change these view to their desired effect.

Android native ListView does not support sliding around, but see the micro-letter phone book, the contact can be left and right to operate, through their own ideas and ideas, and to achieve.

Ideas:
1. Get the x,y position where the finger is placed on the screen and judge the position that clicked in the ListView.
2. Judge the direction of the slide, if it is the upper and lower direction, touch events to listview treatment, if it is left and right direction, it is prohibited to ListView slide.
3. Move the selected view according to the movement of the finger.
4. After the slide is over, turn the view back.
5. Through the incoming listener, tell the user whether to slide left or right.

Effect Chart:

Re-listview Code:

Package Com.example.wz.view;
Import Android.annotation.SuppressLint;
Import Android.content.Context;
Import Android.os.Handler;
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.TextView;
Import COM.EXAMPLE.WZ.R;
Import Com.example.wz.util.MyLog;
Import Com.example.wz.util.OpenLooper;

Import Com.example.wz.util.OpenLooper.LoopCallback;

 public class Mylistview extends ListView {public MyLog log = new MyLog (this, true);

 public float screenwidth;

 public int mtouchslop;

 public float density;
 Public Mylistview {Super (context);
 Public Mylistview (context, AttributeSet attrs) {This (context, attrs, 0);
 public float transletespeed = 2f;
 Public Openlooper openlooper = null; Public Loopcallback loopcalLback = null; @SuppressWarnings ("deprecation") public mylistview (context, AttributeSet attrs, int defstyle) {Super (context,
  Attrs, Defstyle); This.screenwidth = ((WindowManager) Context.getsystemservice (Context.window_service)). GetDefaultDisplay ().
  GetWidth ();
  This.mtouchslop = Viewconfiguration.get (GetContext ()). Getscaledtouchslop ();
  This.density = Context.getresources (). Getdisplaymetrics (). density;
  This.openlooper = new Openlooper ();
  This.openLooper.createOpenLooper ();
  This.loopcallback = new Listloopcallback (this.openlooper);
 This.openLooper.loopCallback = This.loopcallback;
  public class Bodystatus {public int None = 0, down = 1, move = 2, up = 3, homing = 4;
 int state = None;

 Public Bodystatus bodystatus = new Bodystatus ();
  public class Removedirection {public int None = 0, left = 1, right = 2, Homing_left = 3, homing_right = 4;
 public int state = None;

 Public removedirection removedirection = new Removedirection (); Public CLASS Listloopcallback extends Loopcallback {public listloopcallback (Openlooper openlooper) {openlooper.super (); @Override public void loop (double ellapsedmillis) {if (bodystatus.state = = bodystatus.homing) {gohoming (f
   loat) ellapsedmillis);
  }} public void gohoming (float delta) {Float distance = (float) delta * transletespeed;
   if (removedirection.state = = removedirection.left) {Float CurrentX = itemview.getscrollx () + distance;
   if (CurrentX > screenwidth) {distance = distance-(currentx-screenwidth);
   } itemview.scrollby ((int) (distance), itemview.getscrolly ());  if (ITEMVIEW.GETSCROLLX () > SCREENWIDTH/2 + * screenwidth/1080) {T2.settranslationx (ITEMVIEW.GETSCROLLX ()-
   SCREENWIDTH/2-3f);
   else {T2.settranslationx (3f);
   } else if (removedirection.state = = removedirection.right) {Float CurrentX = itemview.getscrollx ()-distance; if (CurrentX <-screenwidth) {distance = Distance-(Math.Abs (CurrentX)-screenwidth);
   } itemview.scrollby ((int) (-distance), itemview.getscrolly ()); if (ITEMVIEW.GETSCROLLX () <-(SCREENWIDTH/2 + 3f * 2)) {T1.settranslationx (-(Math.Abs) (ITEMVIEW.GETSCROLLX ()
   )-SCREENWIDTH/2-3f));
   else {T1.settranslationx ( -40 * 3f); } else if (removedirection.state = removedirection.homing_left) {Float CurrentX = itemview.getscrollx ()-Distanc
   E
   if (CurrentX < 0) {distance = distance-(Math.Abs (CurrentX));
  } itemview.scrollby ((int) (-distance), itemview.getscrolly ());
   else if (removedirection.state = = removedirection.homing_right) {Float CurrentX = itemview.getscrollx () + distance;
   if (CurrentX > 0) {distance = Distance-currentx;
  } itemview.scrollby ((int) (distance), itemview.getscrolly ());  } if (itemview.getscrollx () = = 0 | | itemview.getscrollx () >= screenwidth | | itemview.getscrollx () <=-screenWidth)
   {openlooper.stop ();if (ITEMVIEW.GETSCROLLX () >= screenwidth) {Mremovelistener.removeitem (removedirection, position);
   else if (ITEMVIEW.GETSCROLLX () <=-screenwidth) {Mremovelistener.removeitem (removedirection, position); New Handler (). postdelayed (New Runnable () {@Override public void run () {Itemview.scrollto 0, Itemview.
     Getscrolly ());
    Bodystatus.state = Bodystatus.none;
  }, 300);
 } public int touch_down_x;

 public int touch_down_y;
 Public View Itemview;
 public TextView T1;

 public TextView T2;
 public int snap_velocity = 800;

 public int position;

  @Override public boolean dispatchtouchevent (Motionevent event) {int action = event.getaction ();
   if (action = = Motionevent.action_down) {//Addvelocitytracker (event);
   if (bodystatus.state!= bodystatus.none) {return super.dispatchtouchevent (event);
   } this.touch_down_x = (int) event.getx ();

   this.touch_down_y = (int) event.gety (); Position = Pointtoposition (ToucH_down_x, touch_down_y);
   if (position = = adapterview.invalid_position) {return super.dispatchtouchevent (event);
   } Itemview = Getchildat (Position-getfirstvisibleposition ());
   T2 = (TextView) Itemview.findviewbyid (R.ID.T2);
  T1 = (TextView) Itemview.findviewbyid (R.ID.T1); else if (action = = motionevent.action_move) {if Math.Abs (getscrollvelocity ()) > Snap_velocity | |  (Math.Abs (Event.getx ()-touch_down_x) > Mtouchslop && math.abs (event.gety ()-touch_down_y) < Mtouchslop))
   {isslide = true;
   } else if (action = = motionevent.action_up) {int velocityx = getscrollvelocity (); if (Math.Abs (Velocityx) > Snap_velocity) {if (Velocityx > snap_velocity) {bodystatus.state = BodyStatus.H
     oming;
     Removedirection.state = Removedirection.right;
    Openlooper.start ();
     else {bodystatus.state = bodystatus.homing;
     Removedirection.state = Removedirection.left;
    Openlooper.start ();
    }} else {if (ITEMVIEW.GETSCROLLX () >= screenwidth/2) {bodystatus.state = bodystatus.homing;
     Removedirection.state = Removedirection.left;
    Openlooper.start ();
     else if (ITEMVIEW.GETSCROLLX () <=-screenwidth/2) {bodystatus.state = bodystatus.homing;
     Removedirection.state = Removedirection.right;
    Openlooper.start ();
     else {if (ITEMVIEW.GETSCROLLX () < 0) {removedirection.state = Removedirection.homing_right;
     else {removedirection.state = Removedirection.homing_left;
     } bodystatus.state = bodystatus.homing;
    Openlooper.start ();
   } recyclevelocitytracker ();
  Isslide = false;
 Return Super.dispatchtouchevent (event);

 public Boolean isslide = false;  @SuppressLint ("recycle") @Override public boolean ontouchevent (Motionevent event) {if (isslide && position!=
   adapterview.invalid_position) {requestdisallowintercepttouchevent (true);
   Addvelocitytracker (event); int x = (int) event.getx ();
   int action = Event.getaction (); if (action = = Motionevent.action_down) {} else if (action = = motionevent.action_move) {motionevent CancelEvent =
    Motionevent.obtain (event); Cancelevent.setaction (Motionevent.action_cancel |
    (Event.getactionindex () << motionevent.action_pointer_index_shift));

    Ontouchevent (CancelEvent);
    int deltax = touch_down_x-x;
    touch_down_x = x; if (ITEMVIEW.GETSCROLLX () > SCREENWIDTH/2 + 3f * 2) {T2.settranslationx (ITEMVIEW.GETSCROLLX ()-Screenwidt
    H/2-3f);
    else {T2.settranslationx (3f); } if (Itemview.getscrollx () <-(SCREENWIDTH/2 + 3f * 2)) {T1.settranslationx (-(Math.Abs ITEMVIEW.GETSC
    ROLLX ())-SCREENWIDTH/2-3f));
    else {T1.settranslationx ( -40 * 3f);
    } itemview.scrollby (DeltaX, 0);
   return true;
 } return Super.ontouchevent (event);

 Public RemoveListener Mremovelistener; public void SetremoveListener (RemoveListener removelistener) {this.mremovelistener = RemoveListener;
 Public interface RemoveListener {public void RemoveItem (removedirection direction, int position);

 Public Velocitytracker Velocitytracker; public void Addvelocitytracker (Motionevent event) {if (Velocitytracker = null) {Velocitytracker = Velocitytracker.
  Obtain ();
 } velocitytracker.addmovement (event);
   public int getscrollvelocity () {if (Velocitytracker!= null) {velocitytracker.computecurrentvelocity (1000);
   int velocity = (int) velocitytracker.getxvelocity ();
  return velocity;
 return 0;
   public void Recyclevelocitytracker () {if (Velocitytracker!= null) {velocitytracker.recycle ();
  Velocitytracker = null;

 }
 }
}

to test the ListView activity code:

Package com.example.wz;

Import java.util.ArrayList;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.DisplayMetrics;
Import Android.util.Log;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.BaseAdapter;

Import Android.widget.TextView;
Import Com.example.wz.view.MyListView;
Import com.example.wz.view.MyListView.RemoveDirection;

Import Com.example.wz.view.MyListView.RemoveListener;

 public class Testlistactivity extends activity {layoutinflater minflater;
  @Override protected void OnCreate (Bundle savedinstancestate) {displaymetrics = new displaymetrics ();
  This.getwindowmanager (). Getdefaultdisplay (). Getmetrics (Displaymetrics);
  Super.oncreate (savedinstancestate);
  Setcontentview (r.layout.activity_testlist);
  Minflater = Getlayoutinflater ();
  ListView = (Mylistview) Findviewbyid (R.id.slidecutlistview);
 Showaddressdialog ();

 Public Displaymetrics Displaymetrics; MylistviewListView;

 public arraylist<string> items; public void Showaddressdialog () {items = new arraylist<string> () {Add ("Item ...)
    1 "); Add ("Item ...")
    2 "); Add ("Item ...")
    3 "); Add ("Item ...")
    4 "); Add ("Item ...")
    5 "); Add ("Item ...")
    6 "); Add ("Item ...")
    7 "); Add ("Item ...")
    8 "); Add ("Item ...")
    9 "); Add ("Item ...")
    10 "); Add ("Item ...")
    11 "); Add ("Item ...")
    12 "); Add ("Item ...")
    13 "); Add ("Item ...")
    14 "); Add ("Item ...")
    15 "); Add ("Item ...")
    16 "); Add ("Item ...")
    17 "); Add ("Item ...")
    18 "); Add ("Item ...")
    19 "); Add ("Item ...")
   20 ");

  }
  };
  Nearbyrelationadapter nearbyrelationadapter = new Nearbyrelationadapter ();
  Listview.setadapter (Nearbyrelationadapter); Listview.setremovelistener (New RemoveListener () {@Override public void RemoveItem (removedirection direction, int p Osition) {if (direction.state = = direction.
    left) {log.e ("A", "left" + "-" + position); else if (direction.state = direction. right) {LOG.E ("A", "right" + "-"+ position);
 }
   }
  }); public class Nearbyrelationadapter extends Baseadapter {@Override public int getcount () {return items.size ()
  ;
  @Override public Object getitem (int posotion) {return items.get (posotion);
  @Override public long Getitemid (int posotion) {return posotion;
   @Override public View getview (int position, View Convertview, ViewGroup parent) {Holder Holder = null;
    if (Convertview = = null) {holder = new holder ();
    Convertview = minflater.inflate (r.layout.view_menu_item1, NULL);
    Holder.title = (TextView) Convertview.findviewbyid (r.id.title);
    Holder.o1 = Convertview.findviewbyid (R.ID.O1);
    Holder.o1.setTranslationX (-displaymetrics.widthpixels);
    Holder.o2 = Convertview.findviewbyid (R.ID.O2);
    Holder.o2.setTranslationX (Displaymetrics.widthpixels);
   Convertview.settag (holder);
   else {holder = (holder) Convertview.gettag ();
   } holder.title.setText (Items.get (position)); ConveRtview.scrollto (0, convertview.getscrolly ());
  return convertview;
   Class Holder {TextView title;
  View O1, O2;

 }
 }
}

ListView Layout File:

<?xml version= "1.0" encoding= "Utf-8"?> <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.wz.view.MyListView
  android:id= "@+id/slidecutlistview"
  android:layout_width= "Match_parent"
  android:layout_height= "match_parent"
  android:cachecolorhint= "@android: Color/transparent"
  Android:listselector= "@android: Color/transparent" >
 </com.example.wz.view.MyListView>

 < TextView
  android:layout_width= "1DP"
  android:layout_height= "match_parent"
  android:layout_ Centerhorizontal= "true"
  android:background= "#0099cd"/>

</RelativeLayout>

Item layout for ListView:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:background=" #fff "> & Lt Relativelayout android:id= "@+id/o1" android:layout_width= "match_parent" android:layout_height= "60DP" android:backg round= "#ff0000" > <textview android:id= "@+id/t1" android:layout_width= "80DP" android:layout_height= "wrap
   _content "android:layout_alignparentright=" true "android:layout_centervertical=" true "android:gravity=" center " android:padding= "10DP" android:text= "delete" android:textcolor= "#99000000" android:textsize= "18sp"/> </relat ivelayout> <relativelayout android:id= "@+id/o2" android:layout_width= "Match_parent" android:layout_height= "6 0DP "android:background=" #660099cd > <textview android:id= "@+id/t2" android:layout_width= "80DP" Andro id:layout_height= "Wrap_content"
   Android:layout_alignparentleft= "true" android:layout_centervertical= "true" android:gravity= "center" android:p adding= "10DP" android:text= "edit" android:textcolor= "#99000000" android:textsize= "18sp"/> </relativelayout&

 Gt <relativelayout android:id= "@+id/r1" android:layout_width= "match_parent" android:layout_height= "60DP" android:b ackground= "#fff" > <textview android:id= "@+id/title" android:layout_width= "Match_parent" Android:layout_ height= "Wrap_content" android:layout_centervertical= "true" android:gravity= "Center_vertical" android:textColor= "#
 99000000 "android:textsize=" 18sp "/> </RelativeLayout> </RelativeLayout>

Other classes used in the code, in the previous article: http://www.jb51.net/article/83822.htm

Reprinted from: http://blog.csdn.net/qxs965266509

The above is the entire content of this article, I hope to help you learn.

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.