Android basic getting started tutorial -- 3.4 TouchListener PK OnTouchEvent + multi-point touch, androidontouchevent

Source: Internet
Author: User
Tags gety

Android basic getting started tutorial -- 3.4 TouchListener PK OnTouchEvent + multi-point touch, androidontouchevent
Basic Android tutorial -- 3.4 TouchListener PK OnTouchEvent + multi-point touch

Tags (separated by spaces): basic Android tutorial

This section introduces:

For example, what this section brings to you is:TouchListenerAndOnTouchEventComparison, as well as multi-point touch knowledge point!
TouchListener is listener-based, while OnTouchEvent is callback-based! Below are two simple examples to deepen
Everyone's understanding!

1. sample listening-based TouchListener code:


Implementation Code:
Main. xml

<RelativeLayout xmlns:android=""      xmlns: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 {private ImageView imgtouch; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_my); imgtouch = (ImageView) findViewById (R. id. imgtouch); imgtouch. setOnTouchListener (new View. onTouchListener () {@ Override public boolean onTouch (View v, MotionEvent event) {Toast. makeText (GetApplicationContext (), "You touched lunjia through the listener mode: OnTouchListener ~ ", Toast. LENGTH_LONG). show (); return true ;}});}}

Code parsing:

You can simply set an ImageView, setOnTouchListener, and rewrite the onTouch method! It's very simple. In fact, there is already an example in the frame layout section. Do you still remember the cute girl who moved her fingers?

OnTouchListener related methods and attributes:

OnTouch(View v, MotionEvent event): In turn, the parameters here are the components that trigger the touch event and touch the event.
It encapsulates the details of the trigger event, including the event type, trigger time, and other information. For example, event. getX (), event. getY ()
We can also judge the touch action type and use event. getAction () to judge it. For example:
Event. getAction = MotionEvent.ACTION_DOWN, Press the event
Event. getAction = MotionEvent.ACTION_MOVE: Mobile event
Event. getAction = MotionEvent.ACTION_UP: Events

2. onTouchEvent () method based on callback

It is also a touch event, but onTouchEvent is mostly used for custom views. This method is overwritten in all view classes, and this kind of touch event is based on callback, that is: if the returned value is false, the event will continue to be propagated and processed by the external container or Activity! Of course, Gesture is also involved, which will be explained in detail later! OnTouchEvent is actually similar to onTouchListener, but the processing mechanism is not needed. The former is callback, and the latter is the listening mode!

Sample Code:
Define a simple view, draw a small blue circle, and move with your fingers

Implementation Code:
MyView. java

Public class MyView extends View {public float X = 50; public float Y = 50; // create Paint paint Paint = new Paint (); 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, 30, paint) ;}@ Override public boolean onTouchEvent (MotionEvent event) {this. X = event. getX (); this. Y = event. getY (); // The Notification component redraws this. invalidate (); return true ;}}

Main. xml:

<RelativeLayout xmlns:android=""      xmlns:tools=""      android:layout_width="match_parent"      android:layout_height="match_parent"      tools:context=".MyActivity">      <          android:layout_width="wrap_content"          android:layout_height="wrap_content" />  </RelativeLayout>  


Move with your fingers ~

3. Multi-point touch principle:

The so-called multi-point touch means that multiple fingers are operated on the screen. The most common estimation is the zoom-in function. For example, many image browsers support zoom-in! In theory, the Android system can handle the touch of up to 256 fingers. Of course, this depends on the support of mobile phone hardware. However, mobile phones that support multi-point touch generally support 2-4 points, of course, more! We found that the previous two points are useful to MotionEvent. MotionEvent represents a touch event.Event. getAction () & MotionEvent. ACTION_MASKIn addition to the three single-point operations described above, there are two dedicated operations:

  • MotionEvent.ACTION_POINTER_DOWN: When there is already a point on the screen, it is triggered when another point is pressed.
  • MotionEvent.ACTION_POINTER_UP: Triggered when multiple points are held down and one point is released (that is, not the last point is opened ).

The simple process is like this:

  • When one of our fingers touch the screen --> trigger the ACTION_DOWN event
  • Another finger also touched the screen --> trigger ACTION_POINTER_DOWN event. If there are other fingers touching, continue to trigger
  • One finger leaves the screen --> triggers the ACTION_POINTER_UP event, and another finger leaves.
  • When the last finger leaves the screen --> triggers the ACTION_UP event
  • In addition, the ACTION_MOVE event will be continuously triggered throughout the process.

We can use event.GetX(Int) or event.GetY(Int) to obtain the positions of different touch points:
For example, event. getX (0) can obtain the X coordinate of the first contact point, and event. getX (1) can obtain the X coordinate of the second contact point...
In addition, we can also callGetPointerCount ()Method to Determine how many fingers are currently being touched ~

Sample Code:

Well, let's write a common example of Single-finger image dragging and double-finger Image Scaling:


Implementation Code:


<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android=""    android:layout_width="match_parent"    android:layout_height="match_parent" >    <ImageView        android:id="@+id/img_test"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:scaleType="matrix"        android:src="@drawable/pic1" /></RelativeLayout>

MainActivity. java

Package com. jay. example. edittextdemo; import android. app. activity; import android. graphics. matrix; import android. graphics. pointF; import android. OS. bundle; import android. util. floatMath; import android. view. motionEvent; import android. view. view; import android. view. view. onTouchListener; import android. widget. imageView; public class MainActivity extends Activity implements OnTouchListener {private ImageView img_test; // controls private Matrix matrix = new Matrix (); private Matrix savedMatrix = new Matrix (); // different States: private static final int NONE = 0; private static final int DRAG = 1; private static final int ZOOM = 2; private int mode = NONE; // define the point of the first press, the focus of the two touchpoints, and the distance between the two fingers in an accident: private PointF startPoint = new PointF (); private PointF midPoint = new PointF (); private float oriDis = 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) {// case MotionEvent. ACTION_DOWN: matrix. set (view. getImageMatrix (); savedMatrix. set (matrix); startPoint. set (event. getX (), event. getY (); mode = DRAG; break; // double case MotionEvent. ACTION_POINTER_DOWN: oriDis = distance (event); if (oriDis> 10f) {savedMatrix. set (matrix); midPoint = middle (event); mode = ZOOM;} break; // open case MotionEvent with your fingers. ACTION_UP: case MotionEvent. ACTION_POINTER_UP: mode = NONE; break; // case MotionEvent of a Single-finger sliding event. ACTION_MOVE: if (mode = DRAG) {// a finger to DRAG the matrix. set (savedMatrix); matrix. postTranslate (event. getX ()-startPoint. x, event. getY ()-startPoint. y);} else if (mode = ZOOM) {// two fingers slide float newDist = distance (event); if (newDist> 10f) {matrix. set (savedMatrix); float scale = newDist/oriDis; matrix. postScale (scale, scale, midPoint. x, midPoint. y) ;}} break;} // sets the Matrix view of the ImageView. setImageMatrix (matrix); return true;} // calculate the distance between two touch points. private float distance (MotionEvent event) {float x = event. getX (0)-event. getX (1); float y = event. getY (0)-event. getY (1); return FloatMath. sqrt (x * x + y * y);} // calculate the point of the two touch points private PointF middle (MotionEvent event) {float x = event. getX (0) + event. getX (1); float y = event. getY (0) + event. getY (1); return new PointF (x/2, y/2 );}}

Okay,TouchListener **And OnTouchEvent ** and multi-point touch here ~

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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: 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.