Android gesturedetector Gesture Slide Use example explain _android

Source: Internet
Author: User
Tags abs touch

Gesture used in ViewGroup

The Gesturedetector class allows us to quickly handle gesture events such as clicks, slides, and so on.
The use of Gesturedetector is divided into three steps:
1. Define Gesturedetector Class
2. Initialize gesture class, simultaneously set gesture monitor
3. Hand over the touch incident to gesture for treatment

Let's take a look at how to use it, followed by an example:

Package Com.example.y2222.myview;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import Android.view.GestureDetector;
Import android.view.MotionEvent;

Import Android.widget.LinearLayout;
 /** * Created by Raise.yang on 2016/06/29. 

 * * public class Gesturedemoview extends LinearLayout {//1, define Gesturedetector class private Gesturedetector m_gesturedetector;
 Public Gesturedemoview (context, AttributeSet attrs) {This (context, attrs, 0); 
  Public Gesturedemoview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
  Set to clickable setclickable (true);
  2, the initialization gesture class, while setting gesture monitoring m_gesturedetector = new Gesturedetector (context, ongesturelistener);
 Double-click Listening-generally rarely used to m_gesturedetector.setondoubletaplistener (Ondoubletaplistener); @Override public boolean ontouchevent (Motionevent event) {//3, handing the touch event to gesture processing m_gesturedetector.ontouchevent
  (event);
 Return Super.ontouchevent (event); }//EarlyTo start the gesture listener object, use the Gesturedetector.ongesturelistener implementation abstract class, because the actual development of many methods are not used in private final gesturedetector.ongesturelistener  Ongesturelistener = new Gesturedetector.simpleongesturelistener () {@Override public boolean onsingletapup (motionevent
   e) {log.d ("Gesturedemoview", "Onsingletapup ()");
  Return Super.onsingletapup (e);
   @Override public void onlongpress (Motionevent e) {log.d ("Gesturedemoview", "onlongpress ()");
  Super.onlongpress (e); @Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey) {log.d ("Ges
   Turedemoview "," onscroll () Distancex = "+ Distancex);
  Return Super.onscroll (E1, E2, Distancex, Distancey); @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {log.d ("Gest
   Uredemoview "," onfling () Velocityx = "+ Velocityx);
  Return Super.onfling (E1, E2, Velocityx, Velocityy); @Override public void onshowpress (Motionevent e) {log.d ("GestuRedemoview "," onshowpress () ");
  Super.onshowpress (e);
   @Override public boolean Ondown (Motionevent e) {log.d ("Gesturedemoview", "Ondown ()");
  Return Super.ondown (e);
   @Override public boolean Ondoubletap (Motionevent e) {log.d ("Gesturedemoview", "Ondoubletap ()");
  Return Super.ondoubletap (e);
   @Override public boolean ondoubletapevent (Motionevent e) {log.d ("Gesturedemoview", "Ondoubletapevent ()");
  Return Super.ondoubletapevent (e); @Override public boolean onsingletapconfirmed (Motionevent e) {log.d ("Gesturedemoview", onsingletapconfirmed ()
   ");
  Return super.onsingletapconfirmed (e);
   @Override public boolean onContextClick (Motionevent e) {log.d ("Gesturedemoview", "onContextClick ()");
  Return Super.oncontextclick (e);
 }
 }; Private final Gesturedetector.ondoubletaplistener Ondoubletaplistener = new Gesturedetector.ondoubletaplistener () {@ Override public boolean onsingletapconfirmed (Motionevent e) {LoG.D ("Gesturedemoview", "onsingletapconfirmed () Ondoubletaplistener");
  return false; @Override public boolean Ondoubletap (Motionevent e) {log.d ("Gesturedemoview", Ondoubletap () ondoubletaplistene
   R ");
  return false; @Override public boolean ondoubletapevent (Motionevent e) {log.d ("Gesturedemoview", Ondoubletapevent () ondouble
   Taplistener ");
  return false;

}
 };

 }

Note:setclickable (TRUE); it must be added, or you will only receive the following example 3 events, the whole long time to find out why. (⊙﹏⊙) b

For the click, double-click, drag, and so on event calls see the following figure:

According to the diagram above, each method is generally called, indicating several easily confused callback methods
1. onscroll ()
Public boolean onscroll (Motionevent E1, motionevent E2, float Distancex, float distancey)
E1: The starting point of the sliding event (i.e. Ondown ())
E2: Current sliding position (position of finger)
Distancex: The distance px from the last slide (call onscroll) to the x-axis of the slide, not the x-axis distance from the E1 point to the E2 point
Distancey: The distance px from the last slide (call onscroll) to the Y axis of this slide, not the y-axis of the E1 point to the E2 point
2. onfling ()
public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy)
E1: Drag the start of the event (that is, Ondown ())
When E2:onfling () is called, the position of the finger
Slide pixel value per second on velocityx:x axis
Slide pixel value per second on velocityy:y axis
Note: onfling () is invoked when the drag rate Velocityx or velocityy exceeds the viewconfiguration.getminimumflingvelocity () minimum drag rate. That is, if you drag only a little, or drag slowly, this method will not be triggered.
Corresponding Source:

  if (Math.Abs (velocityy) > mminimumflingvelocity)
      | | (Math.Abs (Velocityx) > Mminimumflingvelocity)) {
     handled = mlistener.onfling (mcurrentdownevent, Ev, Velocityx, velocityy);
    }

Practice: use Gesturedetector to implement left-slip deletion

In many ListView have this effect, now realize their own, by the way familiar with the use of gesturedetector.
Effect Chart:

Gesturedemoview.java:

Package Com.example.y2222.myview;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import Android.view.GestureDetector;
Import Android.view.LayoutInflater;
Import android.view.MotionEvent;

Import Android.widget.LinearLayout;

Import COM.EXAMPLE.Y2222.MYAPPLICATION.R;
 /** * Created by Raise.yang on 2016/06/29. 

 * * public class Gesturedemoview extends LinearLayout {//1, define Gesturedetector class private Gesturedetector m_gesturedetector;

 private int m_max_scrollx;
 Public Gesturedemoview (context, AttributeSet attrs) {This (context, attrs, 0); 
  Public Gesturedemoview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
  Set to clickable setclickable (true);

  2, the initialization gesture class, while setting gesture monitoring m_gesturedetector = new Gesturedetector (context, ongesturelistener);
 Layoutinflater.from (context)-Inflate (r.layout.view_gesture, this); @Override public boolean ontouchevent (Motionevent event) {//3, Will touch eventHanding over to gesture to deal with m_gesturedetector.ontouchevent (event);
   if (event.getaction () = = motionevent.action_up) {//Gesturedetector does not have a method to handle the up event, it can only be processed here.
   int scrollx = GETSCROLLX ();
   if (Scrollx > M_max_scrollx/2) {show_right_view ();
   else {Hide_right_view ();
 } return Super.ontouchevent (event);  @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec,
  HEIGHTMEASURESPEC);
  int childcount = Getchildcount (); for (int i = 0; i < ChildCount i++) {//measuring the width of the child view?
   Do not measure, the right layout will not show, here is a bit of doubt Measurechild (Getchildat (i), Widthmeasurespec, Heightmeasurespec);
   if (i = = 1) {m_max_scrollx = Getchildat (i). Getmeasuredwidth (); }///Initialize Gesture Listener object, using Gesturedetector.ongesturelistener implementation abstract class, because many methods in actual development are not used in private final Gesturedetector.ongestureli Stener Ongesturelistener = new Gesturedetector.simpleongesturelistener () {@Override public boolean onscroll (Motionev ENT E1, motionevent E2, float Distancex, float Distancey) {log.d ("Gesturedemoview", "onscroll () Distancex =" + Distancex + "GETSCROLLX =" + GetS
   CROLLX () + "MAX_SCROLLX =" + m_max_scrollx);
   int scrollx = GETSCROLLX ();
   int minscrollx =-SCROLLX;
   int maxscrolly = M_MAX_SCROLLX-SCROLLX;
   The distance boundary control for sliding is if (Distancex > maxscrolly) {Distancex = maxscrolly;
   else if (Distancex < MINSCROLLX) {Distancex = MINSCROLLX;
   } scrollby ((int) Distancex, 0);
  return true; @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy) {log.d ("Gest
   Uredemoview "," onfling () Velocityx = "+ Velocityx);
   if (Velocityx < 0) {//Fast Left sliding show_right_view ();
   else {Hide_right_view ();
  Return Super.onfling (E1, E2, Velocityx, Velocityy);

 }
 };
 private void Show_right_view () {scrollto (m_max_scrollx, 0);
 private void Hide_right_view () {scrollto (0, 0);

 }

}

View_gesture.xml

<?xml version= "1.0" encoding= "Utf-8"?> <merge xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  android:layout_width=" match_parent "
  android:layout_height=" wrap_content "
  android:o rientation= "Horizontal" >

 <textview
  android:layout_width= "match_parent"
  android:layout_height = "Wrap_content"
  android:gravity= "center"
  android:text= "left layout"/>

 <linearlayout
  android: Layout_width= "Wrap_content"
  android:layout_height= "match_parent"
  android:orientation= "Horizontal"
  >

  <button
   android:layout_width= "wrap_content"
   android:layout_height= "Wrap_content"
   android:text= "collection"/>

  <button
   android:layout_width= "wrap_content"
   android:layout_ height= "Wrap_content"
   android:text= "delete"/>
 </LinearLayout>
</merge>

The root tag in the XML file uses <MERGE>, which reduces the level of view tree nesting and uses getchildcount () to get the number of child view we want.

For more information on the use of <merge> labels, please refer to Guo Shen blog:http://blog.csdn.net/guolin_blog/article/details/43376527

The implementation is also very simple, when scroll and fling, get the sliding distance or sliding speed, and then call view their own scrollto () or Scrollby () sliding internal elements can be.
From the effect diagram, when sliding to half let go, immediately slide to the left, there is no animation, this experience is poor, so you need to optimize. For more animation effects when sliding, you can use the Scroller class to complete, ready for the next period of completion.

Gesture used in view

As in ViewGroup, in view, the same is accomplished through three steps:
1. Define Gesturedetector Class
2. Initialize gesture class, simultaneously set gesture monitor
3. Hand over the touch incident to gesture for treatment
Give a Litchi:
Do a small ball follow the effect of the finger movement, first draw the ball, when the finger on the ball slide, will call Onscroll (), in this method, modify the center of the position of the redraw, so that the ball can move.
Here are 2 key points:
1. How to judge the finger falls on the ball;
2. When sliding to the boundary, it cannot exceed the boundary;

Effect Chart:

Gestureview.java Code:

Package Com.example.y2222.myview;
Import Android.content.Context;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.util.AttributeSet;
Import Android.view.GestureDetector;
Import android.view.MotionEvent;

Import Android.view.View;
 /** * Created by Raise.yang on 2016/07/05.
 * * public class Gestureview extends View {private Gesturedetector m_gesturedetector;
 Private Paint M_paint;
 The center point of the ball is private float centerx;
 private float centery;
 The radius of the ball is private int radius;

 Whether touch the small ball on the private Boolean touch_bool;
 Public Gestureview (context, AttributeSet attrs) {This (context, attrs, 0);
  Public Gestureview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
  The initial brush m_paint = new paint (Paint.anti_alias_flag); M_paint.setcolor (Getresources (). GetColor (Android).
  R.color.holo_blue_light));
  Set to clickable setclickable (true); 2, initialize the gesture class while setting gesture monitoring m_gesturedetector = new Gesturedetector (context, onGesturelistener);
 RADIUS = 50; @Override public boolean ontouchevent (Motionevent event) {//3, handing the touch event to gesture processing m_gesturedetector.ontouchevent
  (event); if (event.getaction () = = Motionevent.action_down) {//judge the finger falls on the ball if (getdistancebypoint (int) CenterX, (int) centery
   , (int) event.getx (), (int) event.gety ()) < radius) {Touch_bool = true;
   else {Touch_bool = false;
 } return Super.ontouchevent (event);  @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {//The default center of the circle in the central point if (W > 0) {CenterX
  = W/2;
  } if (H > 0) {centery = H/2;
 } @Override protected void OnDraw (Canvas Canvas) {canvas.drawcircle (CenterX, CenterY, radius, m_paint); } gesturedetector.ongesturelistener Ongesturelistener = new Gesturedetector.simpleongesturelistener () {@Override PU  Blic boolean onscroll (motionevent E1, motionevent E2, float Distancex, float distancey) {if (Touch_bool) {CenterY
-= Distancey;    CenterX-= Distancex;
    Handling boundary Issues if (CenterX < radius) {CenterX = radius;
    else if (CenterX > GetWidth ()-radius) {CenterX = GetWidth ()-radius;
    } if (CenterY < radius) {centery = radius;
    else if (CenterY > GetHeight ()-radius) {centery = GetHeight ()-radius;
   ///Change center, notify redraw Postinvalidate ();
  return true;

 }
 };  /** * Calculates the distance between two points */private int getdistancebypoint (int x1, int y1, int x2, int y2) {Double temp = Math.Abs ((x2-x1)
  * (X2-X1)-(y2-y1) * (y2-y1));
 return (int) math.sqrt (temp);

 }

}

In the process of problem 1 o'clock, I set a Boolean value, in the user's touch to determine whether the current point and center point distance is less than the radius, if less than, the description in the circle. So in the sliding time, to determine whether the need to slide the ball.
Control boundary, in fact, is to control the coordinates of the center point, as long as the guarantee Fall (Radius,radius), (GetWidth ()-radius,getheight ()-radius) two-point rectangle.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.