In this post I explain a simple example of an implementation of a double tap event on an ImageView that can be adapted with some changes for a TextView or an Activity.
-
- MainActivity.java, the main activity
12345678910111213package eu.lucazanini.doubletap;import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}} - res/layout/activity_main.xml, il layout per l’activity principale
123456789101112131415<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/LinearLayout1"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"><eu.lucazanini.doubletap.DoubleTapViewandroid:id="@+id/imageView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_launcher"android:layout_gravity="center" /></LinearLayout>
at the line 8 there is a View linked to the class DoubleTapView that extends an ImageView
- MainActivity.java, the main activity
- DoubleTapView.java
123456789101112131415161718192021222324252627282930313233343536373839404142]package eu.lucazanini.doubletap;import android.content.Context;import android.support.v4.view.GestureDetectorCompat;import android.util.AttributeSet;import android.util.Log;import android.view.GestureDetector;import android.view.MotionEvent;import android.widget.ImageView;public class DoubleTapView extends ImageView {private class MyGestureListener extendsGestureDetector.SimpleOnGestureListener {@Overridepublic boolean onDoubleTap(MotionEvent event) {Log.d(TAG, "onDoubleTap");return true;}@Overridepublic boolean onDown(MotionEvent event) {return true;}}private final static String TAG = DoubleTapView.class.getName();private GestureDetectorCompat mDetector;public DoubleTapView(Context context, AttributeSet attrs) {super(context, attrs);mDetector = new GestureDetectorCompat(context, new MyGestureListener());}@Overridepublic boolean onTouchEvent(MotionEvent e) {return mDetector.onTouchEvent(e);}}
at the line 17 the method onDoubleTap handles the double tap but you need the following four important points:- line 34: creation of an object of the class GestureDetectorCompat (mDetector)
- line 13: the inner class that extends GestureDetector.SimpleOnGestureListener and an object of this class is passed as argument to the constructor of mDetector of the previous point
- line 38: the method onTouchEvent of ImageView is overridden and calls onTouchEvent of GestureDetectorCompat (mDetector)
- line 23: in the inner class that extends GestureDetector.SimpleOnGestureListener the method onDown is overridden and returns true