Easy Tutorial
❮ Android Tutorial Alphaanimation Android Tutorial Vibrator ❯

3.8 Gestures

Category [Android Basic Tutorial]

Introduction to This Section:

No rest on Saturdays, just got back from a haircut, continuing to type away~

Alright, this section brings you the final part of Chapter 3—Gestures. Friends who have used Meizu phones must be familiar with gestures. Sliding towards the screen on both sides of the home button can open the background task list and so on. Using gestures in apps can greatly enhance user experience, such as Scroll gestures for screen scrolling in browsers, and Fling for page-turning in browsers!

Of course, there are pros and cons. Improper gesture operations can cause APP crashes, and frequent occurrences can lead to user dissatisfaction! So whether to add gestures to your app should be considered carefully! In addition, gestures should be distinguished from the previously learned single/multi-touch touches!

Gestures are: continuous touch actions, such as sliding up, down, left, and right on the screen, or drawing some irregular geometric shapes! Android provides support for both types of gesture behaviors:

If your phone is an Android 4.x native Android system, you may be able to see a Gesture Builder APP provided by Google on your phone or tablet. This app allows users to draw a handwritten symbol in a way similar to doodling, making it correspond to a string name! Of course, it's okay if you don't have such a phone, we have an emulator, just try a 4.0 system yourself and you'll know. In addition, we can get the file where the gesture is saved at \mmt\sdcard\gestures! Well, after so much nagging, let's start the main topic!

By the way, post the official API documentation first: GestureDetector


1. The Execution Order of Gesture Interaction in Android

>

Let's take a look at what the above three classes do: MotionEvent: This class is used to encapsulate gesture, touch pen, trackball, and other motion events. It has two important attributes, X and Y, which are used to record the coordinates of the horizontal and vertical axes respectively. GestureDetector: Recognizes various gestures. OnGestureListener: This is a gesture interaction listener interface, which provides multiple abstract methods, and calls the corresponding methods according to the gesture recognition results of GestureDetector.

—The above information is excerpted from: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1020/448.html

2. Detailed Explanation of GestureListener:

From 1, we know that the key to listening to gestures is: GestureListener. It provides us with the following callback methods:

>

After knowing the relevant methods of GestureListener, implementing gesture detection is also very simple, and the steps are as follows:

>

The code is as follows:

public class MainActivity extends AppCompatActivity {

    private MyGestureListener mgListener;
    private GestureDetector mDetector;
    private final static String TAG = "MyGesture";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Instantiate GestureListener and GestureDetector
}else if(e1.getY() - e2.getY() < MIN_MOVE){
                finish();
                Toast.makeText(MainActivity.this,"Close Activity with gesture",Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    }

}

**Result Analysis:** From the comparison above, it can be seen that using SimpleOnGestureListener is simpler than SimpleOnGestureListener. You can override whatever method you want. Additionally, the example is quite simple, so you can try other ways to play with it, such as zooming in on an image through gestures.

---

## 4.Gesture Addition and Recognition:

>

In addition to the gesture detection explained above, Android also allows us to add gestures and provides related recognition APIs;
In Android, GestureLibrary is used to represent the gesture library, and the GestureLibraries utility class is provided to create a gesture library!

**Four static methods to load the gesture library:**

After obtaining the GestureLibraries object, you can use the following methods provided by the object for corresponding operations:

**Related Methods:**

- public void **addGesture** (String entryName, Gesture gesture): Add a gesture named entryName.

- public Set<String> **getGestureEntries** (): Get the names of all gestures in the gesture library.

- public ArrayList<Gesture> **getGestures** (String entryName): Get all gestures corresponding to the entryName.

- public ArrayList<Prediction> **recognize** (Gesture gesture): Recognize all gestures in the current gesture library that match the gesture.

- public void **removeEntry** (String entryName): Delete the gesture corresponding to the entryName in the gesture library.

- public void **removeGesture** (String entryName, Gesture gesture): Delete the gesture in the gesture library that matches both entryName and gesture.

- public abstract boolean **save** (): Call this method to save the gesture library after adding or deleting gestures.

**GestureOverlayView Gesture Editing Component:**

Android provides three listener interfaces for GestureOverlayView, as follows, and the commonly used one is: **OnGesturePerformedListener**; used to respond when the gesture is completed!

---

## 5.Gesture Addition Example:

PS: The example refers to the code from Li Gang's "Android Crazy Lecture Notes"

**Running Effect Picture:**

Well, let's post the implementation code below:

Two layout files: activity_main.xml and dialog_save.xml

activity_main.xml

<LinearLayout 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:orientation="vertical" tools:context=".MainActivity">

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please draw a gesture on the screen below~"
        android:textSize="20sp"/>


<!-- gestureStrokeType controls whether the gesture needs to be completed in one stroke, multiple means allowing multiple strokes -->
&lt;android.gesture.GestureOverlayView
    android:id="@+id/gesture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gestureStrokeType="multiple" />

</LinearLayout>


dialog_save.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:text="Please enter the gesture name:"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edit_name"/>
</LinearLayout>

<ImageView
        android:id="@+id/img_show"
        android:layout_width="128dp"
        android:layout_height="128dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>


**MainActivity.java:**

public class MainActivity extends AppCompatActivity {

private EditText editText;
private GestureOverlayView gesture;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //After obtaining the gesture editing component, set the relevant parameters
    gesture = (GestureOverlayView) findViewById(R.id.gesture);
    gesture.setGestureColor(Color.GREEN);
    gesture.setGestureStrokeWidth(5);
    gesture.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
        @Override
        public void onGesturePerformed(Gesture

public class MainActivity extends AppCompatActivity {

private GestureOverlayView gesture;
private GestureLibrary gestureLibrary;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mContext = MainActivity.this;
    gestureLibrary = GestureLibraries.fromFile("mmt/sdcard/mygestures");
    if (gestureLibrary.load()) {
        Toast.makeText(mContext, "Gesture library loaded successfully", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(mContext, "Failed to load gesture library", Toast.LENGTH_SHORT).show();
    }

    //After obtaining the gesture editor component, set the relevant parameters
    gesture = (GestureOverlayView) findViewById(R.id.gesture);
    gesture.setGestureColor(Color.GREEN);
    gesture.setGestureStrokeWidth(5);
    gesture.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
        @Override
        public void onGesturePerformed(GestureOverlayView gestureOverlayView, final Gesture gesture) {
            //Recognize the gesture that the user has just drawn
            ArrayList<Prediction> predictions = gestureLibrary.recognize(gesture);
            ArrayList<String> result = new ArrayList<String>();
            //Iterate through all found Prediction objects
            for (Prediction pred : predictions) {
                if (pred.score > 2.0) {
                    result.add("Similarity with gesture [" + pred.name + "] is " + pred.score);
                }
            }
            if (result.size() > 0) {
                ArrayAdapter<Object> adapter = new ArrayAdapter<Object>(mContext,
                        android.R.layout.simple_dropdown_item_1line, result.toArray());
                new AlertDialog.Builder(mContext).setAdapter(adapter,null).setPositiveButton("OK",null).show();
            }else{
                Toast.makeText(mContext,"No matching gesture found!",Toast.LENGTH_SHORT).show();
            }
        }
    });
}

}


Also don't forget to add the SD card read permission in the AndroidManifest.xml file:


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> ```


Summary of this section:

Well, this section introduced the Gesture in Android, explaining gesture judgment, gesture addition, and gesture recognition. Most of the examples come from Mr. Li Gang's "Android Crazy Lecture Notes", if you are interested you can check out the book~ Thank you

-1.0 Android Basic Tutorial Introduction

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Building

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial on Basic Operations of Local Repositories

-1.5.2 Git Using GitHub to Set Up a Remote Repository

-1.6 How to Play with 9 (Nine Sister) Images

-1.7 Interface Prototype Design

-1.8 Project Related Analysis (Various Files, Resource Access)

-1.9 Android Program Signing and Packaging

-1.11 Decompiling APK to Obtain Code & Resources

-2.1 The Concept of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text Box) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-[2.3.3

WeChat Follow

❮ Android Tutorial Alphaanimation Android Tutorial Vibrator ❯