The realization method of touch-screen gesture recognition in Android application development _android

Source: Internet
Author: User
Tags abs event listener stub

Many times, the use of touch screen fling, scroll, such as gesture (gesture) operation will make the user experience of the application greatly increased, such as using scroll gestures in the browser to roll the screen, with the Fling in the reader page and so on. In Android, gesture recognition is done through the Gesturedetector.ongesturelistener interface, but William Rummaged through the official Android documentation without finding a relevant example of an API The Touchpaint in the demo is simply referring to the handling of the Ontouch event, which does not involve gestures.

Let's start by defining some concepts, first of all, that the Android event-handling mechanism is based on listener (listener), which is more than what we call touch-screen related events today, through Ontouchlistener. Second, all of the view's subclasses can add listeners to a certain class of events by means of Setontouchlistener (), Setonkeylistener (), and so on. Third, listener are typically provided in a interface (interface) way, which contains one or more abstract (abstract) methods that we need to implement to perform Ontouch (), OnKey (), and so on. In this way, when we set the event listener for a view and implement the abstract method, the program can give the appropriate response through the CALLBAKC function when a particular event is dispatch to the view.

To see a simple example, use the simplest textview to illustrate (in fact, no difference from the skeleton generated in ADT).

public class Gesturetest extends activity implements ontouchlistener{
 
  @Override
  protected void OnCreate (Bundle Savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.main);
 
    Init TextView
    TextView TV = (TextView) Findviewbyid (r.id.page);
    Set Ontouchlistener on TextView
    Tv.setontouchlistener (this);
    Show some text
    tv.settext (r.string.text);
  }
 
  @Override Public
  Boolean Ontouch (View v., motionevent event) {
    Toast.maketext (this, "Ontouch", toast.length_ Short). Show ();
    return false;
  }

We set a ontouchlistener for TextView's instance TV because the Gesturetest class implements the Ontouchlistener interface, so simply give a this as a parameter. The Ontouch approach is to implement the abstract method in Ontouchlistener, as long as we add logical code here to respond when the user touches the screen, as we do here--to make a message.

Here, we can get the types of touch events, including Action_down, Action_move, Action_up, and Action_cancel, through the Motionevent getaction () method. Action_down refers to the touch screen, action_move refers to the touch screen after the movement by the point, Action_up is to release the touch screen, Action_cancel will not be directly triggered by the user (so not in the scope of today's discussion, Please refer to Viewgroup.onintercepttouchevent (motionevent)). With the help of the user's different operation judgment, combining GETRAWX (), Getrawy (), GetX () and gety () and other methods to obtain the coordinates, we can implement such functions as dragging a button, dragging the scroll bar and so on. Standby can look at the Motionevent class of documents, in addition, you can also see the test touchpaint examples.

Back to the point of today, when we capture touch operation, how to identify the user's gesture? Here we need the help of the Gesturedetector.ongesturelistener interface, so our Gesturetest class becomes this way.

public class Gesturetest extends activity implements Ontouchlistener,
    ongesturelistener {
...
}

Then, in the Ontouch () method, we call the Ontouchevent () method of the Gesturedetector to give the captured Motionevent to Gesturedetector To analyze whether there is a suitable callback function to handle the user's gestures.

@Override Public
  Boolean Ontouch (View V, motionevent event) {
    //Ongesturelistener'll analyzes the given motion Event return
    mgesturedetector.ontouchevent (event);
  }

Next, we have implemented the following 6 abstract methods, of which the most useful of course are onfling (), Onscroll () and onlongpress (). I have written the meaning of each gesture of the method represented in the note, and you will see it.

User Touch touch screen, triggered by 1 motionevent action_down @Override public boolean ondown (Motionevent e) {/TODO auto-generated m
    Ethod stub toast.maketext (this, "Ondown", Toast.length_short). Show ();
  return false; }//user Touch touch screen, has not yet loosened or dragged, by a 1 motionevent Action_down trigger//Note and Ondown () the difference, emphasis is not loosened or dragged state @Override public void Onsh Owpress (motionevent e) {//TODO auto-generated Method stub}//User (after touching the touchscreen) is released, triggered by a 1 motionevent action_up @Ov
  Erride public boolean onsingletapup (Motionevent e) {//TODO auto-generated a stub return false; }//The user presses the touchscreen, moves quickly after releasing, by 1 motionevent action_down, multiple action_move, 1 action_up triggers @Override public boolean onfling (Mot Ionevent E1, motionevent E2, float Velocityx, float velocityy) {//TODO auto-generated method stub return F
  Alse; }//user long by touch screen, triggered by multiple motionevent action_down @Override public void onlongpress (Motionevent e) {/TODO Auto-gene Rated method stub}//The user presses the touchscreen and drags it by 1 motionEvent Action_down, multiple action_move triggers @Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex,
  Float Distancey) {//TODO auto-generated method stub return false;
 }

Let's try to do a onfling () event, the meaning of each parameter in the Onfling () method I wrote in the note, and I need to be aware of the fling event's handling code, in addition to the first trigger fling Action_down and the last action In the _move, we can also use the speed of the user's movement on the X or Y axis as a condition. For example, in the following code we do this when the user moves more than 100 pixels, and the x axis moves faster than 200 pixels per second.

 @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, FL Oat velocityy) {//Parameter explanation://E1:1th action_down motionevent//E2: Last Action_move motionevent//velocityx:x axis move speed , pixel/sec/velocityy:y axis moving speed, pixel/sec/Trigger Condition://x axis coordinate shift greater than fling_min_distance, and move speed is greater than fling_min_velocity pixels/sec if (E 1.getX ()-E2.getx () > Fling_min_distance && math.abs (Velocityx) > Fling_min_velocity) {//Fling
  Left Toast.maketext (this, ' fling left ', Toast.length_short). Show ();
    else if (E2.getx ()-E1.getx () > Fling_min_distance && math.abs (Velocityx) > Fling_min_velocity) {
  Fling Right Toast.maketext (this, ' Fling right ', Toast.length_short). Show ();
return false; }

The problem is, if we try to run the program at this time, you'll find that we don't get the results we want, and tracking the execution of the code will find that the onfling () event has not been captured. This is the question that bothers me at first, what is this really about?
I found the answer in the gesture detection of the discussion group that we need to tv.setontouchlistener (this) in OnCreate, and then add the following code.

Tv.setlongclickable (TRUE);

Only in this way can view handle hold (i.e. Action_move, or multiple Action_down) that are different from tap (touch), and we can do so by android:longclickable in the layout definition.

Depth

Let's summarize two things first:

1. Touch the Activity

2. Touch a View

First, say activity,

A, implements Ongesturelistener

B, Gesturedetector mgesturedetector = new Gesturedetector (this);

C, the Ontouchevent method of rewriting activity

@Override Public 
 Boolean ontouchevent (Motionevent event) {return 

mgesturedetector.ontouchevent (event);

}


D, you can capture the Onfling event

Two, individual view

A, implements Ongesturelistener,ontouchlistener

B

 View view = Findviewbyid (R.id.view);
    View.setontouchlistener (this);
    View.setlongclickable (true);
    Gesturedetector mgesturedetector = new Gesturedetector (this);

C, Rewrite is the Ontouch method of implements Ontouchlistener

@Override Public
  Boolean Ontouch (view view, Motionevent event) {
    //TODO auto-generated method stub return
    MG Esturedetector.ontouchevent (event);
  }

D, you can capture the Onfling event

III. realization of Onfling

private float fling_min_distance =;
  private float fling_min_velocity=10;
  @Override Public
  Boolean onfling (motionevent E1, motionevent E2, float Velocityx,
      float velocityy) {
    //TODO auto-generated method Stub
 
    System.out.println ("onfling");
 
    if (E1.getx ()-E2.getx () > Fling_min_distance
        && math.abs (Velocityx) > fling_min_velocity) {
      // Fling
      left System.out.println ("Zuo");
      Toast.maketext (This, "left", Toast.length_short). Show ();
    else if (E2.getx ()-E1.getx () > Fling_min_distance
        && math.abs (Velocityx) > Fling_min_velocity) { c14/>//Fling
      Right System.out.println ("starboard");
      Toast.maketext (This, "right", Toast.length_short). Show ();
 
    return false;
  }

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.