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:
Android provides gesture detection and offers corresponding listeners for gesture recognition!
Android allows developers to add gestures themselves and provides corresponding APIs to recognize user gestures!
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
>
- When the finger touches the screen, a MotionEvent event is triggered!
- This event is monitored by OnTouchListener, and the MotionEvent object can be obtained in its onTouch() method!
- GestureDetector forwards the MotionEvent object to OnGestureListener
- We can get this object through OnGestureListener, then get relevant information and do relevant processing!
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:
>
Press (onDown): The moment when the finger just touches the touch screen, that is, the touch.
Fling (onFling): The action of quickly moving the finger on the touch screen and releasing it.
Long press (onLongPress): The finger is pressed for a period of time and has not been released.
Scroll (onScroll): The finger slides on the touch screen.
Hold (onShowPress): The finger is pressed on the touch screen, and its time range is from the effective press to before the long press.
Lift (onSingleTapUp): The moment the finger leaves the touch screen.
After knowing the relevant methods of GestureListener, implementing gesture detection is also very simple, and the steps are as follows:
>
Step 1: Create a GestureDetector object, and implement GestureListener when creating it.
Step 2: Hand over the TouchEvent event on the Activity or specific component to GestureDetector for processing! Let's write a simple code to verify this process, that is, override the corresponding methods:
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 -->
<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
2.5.8 Detailed Explanation of Notification (Status Bar Notification)
2.6.4 Simple Usage of DrawerLayout (Official Side-Slide Menu)
3.3 A Brief Analysis of the Handler Message Passing Mechanism
3.6 Responding to System Setting Events (Configuration Class)
3.8 Gestures
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragment - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment - Implementation of Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragment - Implementation of Bottom Navigation Bar (Method 3)
5.2.4 Detailed Explanation of Fragment - Bottom Navigation Bar + ViewPager Page Switching
5.2.5 Detailed Explanation of Fragment - Simple Implementation of News (Shopping) App List Fragment
6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
7.1.1 What to Learn in Android Network Programming and Http Protocol
7.1.2 Learning about Android Http Request and Response Headers
[7.1.4 Android HTTP Request
8.3.14 Paint API - Several Enumeration/Constant Values and ShadowLayer Shadow Effect
8.3.17 Detailed Explanation of Canvas API (Part 2) - Collection of Clipping Methods
8.3.18 Detailed Explanation of Canvas API (Part 3) - Matrix and drawBitmapMesh
8.4.3 Android Animation Collection - Property Animation - First Encounter
8.4.4 Android Animation Collection - Property Animation - Another Encounter
11.0 "2015 Latest Android Basic Tutorial" Completion Celebration~
12.2 DrySister Girl Viewing App (First Edition) - 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) - 4. Adding Data Caching (Adding SQLite)
12.5 DrySister Girl Viewing App (First Edition) - 5. Code Review, Adjustment, and Log Class Writing