Android Basics Getting Started tutorial--3.4 touchlistener PK ontouchevent + multi-point touch

Source: Internet
Author: User
Tags gety

Android Basics Getting Started tutorial--3.4 touchlistener PK ontouchevent + multi-point touch

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section:

Title, this section brings you a comparison of Touchlistener and ontouchevent , as well as a multi-touch point of knowledge!
Touchlistener is based on listening, while Ontouchevent is based on callbacks! Here's a two simple example to deepen
Everyone's understanding!

1. Listen-based Touchlistener code example:

Realize:

Implementation code:
Main.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="Match_parent"android:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"Android:paddingbottom="@dimen/activity_vertical_margin"tools:context=". MyActivity "> <imageview android:layout_width="Wrap_content"android:layout_height="Wrap_content"Android:id="@+Id/imgtouch"Android:background="@drawable/touch"/> </relativelayout>

Mainacitivity.java

 Public  class myactivity extends actionbaractivity {      PrivateImageView Imgtouch;@Override      protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);          Setcontentview (r.layout.activity_my);          Imgtouch = (ImageView) Findviewbyid (R.id.imgtouch); Imgtouch.setontouchlistener (NewView.ontouchlistener () {@Override               Public Boolean OnTouch(View V, motionevent event) {Toast.maketext (Getapplicationcontext (),"You through the Listener mode: Ontouchlistener Touch LUN Home ~", Toast.length_long). Show ();return true;      }          }); }  }

Code parsing:

is simply to set a ImageView, and then Setontouchlistener, rewrite the Ontouch method can! Very simple, in fact, this section in the frame layout has an example, remember that with the finger move of the sister?

Ontouchlistener related methods and properties:

OnTouch (View V, motionevent event): This parameter is followed by the component that triggers the touch event, touching the event
Encapsulates the details of the triggering event, including information such as the type of event, the trigger time, and so on. such as Event.getx (), Event.gety ()
We can also judge the action type of the touch, use Event.getaction () and then make a judgment, such as:
Event.getaction = = Motionevent. Action_down, press the event
Event.getaction = = Motionevent. action_move: Move Event
Event.getaction = = Motionevent. action_up: Bounce Event

2. Callback-based Ontouchevent () method

It is also a touch event, but Ontouchevent is more of a custom view, and all of the view classes override the method, and this touch event is based on a callback, which means that if the value we return is false, then the event will continue to propagate outward. Handled by an outside container or activity! Of course also involves the gesture (Gesture), this we will be in the following detailed explanation!ontouchevent actually and Ontouchlistener is similar, only the processing mechanism does not have, the former is the callback, The latter is the listening mode!

code Example:
Define a simple view, draw a small blue circle, and follow your finger to move

Implementation code:
Myview.java

 Public  class MyView extends View{       Public floatX = -; Public floatY = -;//Create brushesPaint paint =NewPaint (); Public MyView(Context Context,attributeset Set) {Super(Context,set); }@Override       Public void OnDraw(Canvas canvas) {Super. OnDraw (canvas);          Paint.setcolor (Color.Blue); Canvas.drawcircle (x, Y, -, paint); }@Override       Public Boolean ontouchevent(Motionevent event) { This. X = Event.getx (); This. Y = Event.gety ();//Notify component to redraw         This. Invalidate ();return true; }  }

Main.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="match_parent"      tools:context=".MyActivity">      <example.jay.com.touch2.MyView          android:layout_width="wrap_content"          android:layout_height="wrap_content" />  </RelativeLayout>  

Realize:

Move with a finger touch ~

3. Multi-Touch principle things:

The so-called multi-touch is the operation of multiple fingers on the screen, the most estimated is the Zoom function bar, such as a lot of image browser support Zoom! Theoretically the Android system itself can handle up to 256 finger touches, of course, depending on the support of the phone hardware, but a multi-touch mobile phone generally supports 2-4 points, of course some more! We found that the previous two points are useful to motionevent,motionevent represents a touch event, before we can follow event.getaction () & Motionevent.action_mask to determine which operation, in addition to the three single-point operations described above, there are two multi-point-specific operations:

  • motionevent. Action_pointer_down : Triggered when a point on the screen has been held down and then pressed at another point.
  • motionevent. Action_pointer_up : When there are multiple points on the screen being held down, the trigger is released when one of the points is loosened (that is, when the last point is not released).

The simple process is like this:

  • When we touch the screen with one finger and trigger the Action_down event
  • Then there's another finger Touch the screen and trigger the Action_pointer_down event, and if there are other finger touches, continue triggering
  • with one finger off the screen-triggering the Action_pointer_up event, continue to have the finger left, continue to trigger
  • when the last finger leaves the screen and triggers the Action_up event
  • and throughout the process, the Action_move event is continuously triggered

We can pass the event. GetX (int) or event. GetY (int) To obtain the position of a different touch point:
For example EVENT.GETX (0) can obtain the x-coordinate of the first contact point, Event.getx (1) obtains the x-coordinate of the second contact point so ...
In addition, we can determine how many fingers are currently touching the Motionevent object by calling the Getpointercount () method.

code example:

OK, let's write one of the most common single-finger drag images, two-finger zoom image Example:

implementation:
~ Tomorrow to fill up

Implementation code:

Activity_main.xml:

<?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="Match_parent" >            <ImageViewandroid:id="@+id/img_test"android:layout_width="Match _parent "android:layout_height=" Match_parent "android:scaletype=" Matrix "  android:src="@drawable/pic1" />                                        </relativelayout>

Mainactivity.java

 PackageCom.jay.example.edittextdemo;Importandroid.app.Activity;ImportAndroid.graphics.Matrix;ImportAndroid.graphics.PointF;ImportAndroid.os.Bundle;ImportAndroid.util.FloatMath;ImportAndroid.view.MotionEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnTouchListener;ImportAndroid.widget.ImageView; Public  class mainactivity extends Activity implements Ontouchlistener  {    PrivateImageView img_test;//Compression control    PrivateMatrix Matrix =NewMatrix ();PrivateMatrix Savedmatrix =NewMatrix ();//representation of different states:    Private Static Final intNONE =0;Private Static Final intDRAG =1;Private Static Final intZOOM =2;Private intmode = NONE;//define the first pressed point, the focus of the two contact points, and the distance between the two fingers pressed:    PrivatePointF StartPoint =NewPointF ();PrivatePointF midpoint =NewPointF ();Private floatOridis =1F/* * (NON-JAVADOC) * * @see android.app.activity#oncreate (android.os.Bundle) */    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Img_test = (ImageView) This. Findviewbyid (R.id.img_test); Img_test.setontouchlistener ( This); }@Override     Public Boolean OnTouch(View V, motionevent event) {ImageView view = (ImageView) v;Switch(Event.getaction () & Motionevent.action_mask) {//single finger         CaseMotionEvent.ACTION_DOWN:matrix.set (View.getimagematrix ());            Savedmatrix.set (matrix);            Startpoint.set (Event.getx (), event.gety ()); mode = DRAG; Break;//Double finger         CaseMotionEvent.ACTION_POINTER_DOWN:oriDis = Distance (event);if(Oridis >Tenf) {Savedmatrix.set (matrix);                Midpoint = middle (event);            mode = ZOOM; } Break;//Finger release         CaseMOTIONEVENT.ACTION_UP: CaseMotionEvent.ACTION_POINTER_UP:mode = NONE; Break;//single finger swipe event         CaseMotionevent.action_move:if(mode = = DRAG) {//is a finger-draggingMatrix.set (Savedmatrix);            Matrix.posttranslate (Event.getx ()-Startpoint.x, Event.gety ()-STARTPOINT.Y); }Else if(mode = = ZOOM) {//two finger swipe                floatNewdist = Distance (event);if(Newdist >Tenf) {Matrix.set (Savedmatrix);floatscale = Newdist/oridis;                Matrix.postscale (scale, scale, midpoint.x, MIDPOINT.Y); }            } Break; }//Set ImageView matrixView.setimagematrix (matrix);return true; }//Calculate the distance between two touch points    Private float Distance(Motionevent event) {floatx = Event.getx (0)-Event.getx (1);floaty = event.gety (0)-Event.gety (1);returnFLOATMATH.SQRT (x * x + y * y); }//Calculate the midpoint of two touch points    PrivatePointFMiddle(Motionevent event) {floatx = Event.getx (0) + EVENT.GETX (1);floaty = event.gety (0) + event.gety (1);return NewPointF (X/2, Y/2); }}
This section summarizes:

All right, about touchlistener** and ontouchevent** and the multi-touch.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--3.4 touchlistener PK ontouchevent + multi-point touch

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.