Gestures
Introduction to this section:
I don’t have a day off on Saturdays. I just came back from getting a haircut and continue to code~
Okay, this section brings you some information. It is the last section of Chapter 3 - Gestures, Friends who have used Meizu mobile phones must be familiar with gestures. Swipe on both sides of the home button like on the screen. You can open the background task list, etc. Using gestures to operate in the application will greatly improve the user experience. For example, the Scroll gesture can scroll the screen in the browser, Fling can change pages in the browser, etc.!
Of course, there are advantages and disadvantages. For example, inappropriate gesture operations can cause APP Carsh, which often causes user dissatisfaction! So if you want to add gestures to your application, you need to think carefully! In addition, the gestures should be distinguished from the single-finger/multi-finger touch learned earlier!
Gestures are: continuous touching behaviors, such as sliding the screen left and right, up and down, or drawing some irregular geometric figures! Android provides support for both of the above gesture behaviors:
- Android provides gesture detection and provides corresponding listeners for gesture recognition!
- Android running developers add gestures by themselves and provide corresponding APIs to recognize user gestures!
If your phone is a native Android system of Android 4.x, you may be able to see Google on your phone or tablet A Gesture Builder APP is provided, which allows users to draw a handwritten symbol in a way similar to graffiti, making it Corresponds to a string name! Of course, it doesn’t matter if you don’t have such a mobile phone. We have an emulator. Let’s try to open a 4.0 system yourself. That’s it. In addition, we can go to \mmt\sdcard\gestures to get the file that saves the gestures! Okay, so much nagging, let’s get to the point!
By the way, post the official API document first: GestureDetector
1. The execution sequence of gesture interaction in Android
- 1. Finger When the screen is touched, the MotionEvent event is triggered!
- 2. This event is monitored by OnTouchListener, and the MotionEvent object can be obtained in its onTouch() method!
- 3. Forward the MotionEvent object to OnGestureListener through GestureDetector
- 4. We can obtain the object through OnGestureListener, then obtain relevant information and perform related processing!
Let’s take a look at what the above three classes are used for: MotionEvent: This class is used to encapsulate gestures, touch pens, trackballs, etc. Action events. It encapsulates two important attributes X and Y internally, which are used to record the coordinates of the horizontal axis and the vertical axis respectively. GestureDetector: Recognize various gestures. OnGestureListener: This is a listening interface for gesture interaction, which provides multiple abstract methods. And call the corresponding method based on the gesture recognition result of GestureDetector.
——The above information is taken from: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1020/448.html
2. GestureListener detailed explanation:
From 1 we know that the key to monitoring gestures is: GestureListener He provides us with the following callback methods:
- Press (onDown): The moment when your finger touches the touch screen, it is the touch.
- Throwing (onFling): The action of moving your finger quickly on the touch screen and releasing it.
- Long press (onLongPress): The finger is pressed for a period of time and is not released.
- Scroll (onScroll): Finger slides on the touch screen.
- Press and hold (onShowPress): The finger is pressed on the touch screen, and its time range is when the press takes effect, before the long press.
- Lift up (onSingleTapUp): The moment the finger leaves the touch screen.
After knowing the related methods of GestureListener, it is very simple to implement gesture detection. The steps are as follows:
- Step 1: Create a GestureDetector object and create It is necessary to implement GestureListener and pass in
- Step 2: Handle the TouchEvent event on the Activity or specific component to GestureDetector for processing! We write a simple code to verify this process, that is, rewrite the corresponding method:
The code is as follows:
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);
//实例化GestureListener与GestureDetector对象
mgListener = new MyGestureListener();
mDetector = new GestureDetector(this, mgListener);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mDetector.onTouchEvent(event);
}
//自定义一个GestureListener,这个是View类下的,别写错哦!!!
private class MyGestureListener implements GestureDetector.OnGestureListener {
@Override
public boolean onDown(MotionEvent motionEvent) {
Log.d(TAG, "onDown:按下");
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
Log.d(TAG, "onShowPress:手指按下一段时间,不过还没到长按");
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
Log.d(TAG, "onSingleTapUp:手指离开屏幕的一瞬间");
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
Log.d(TAG, "onScroll: Slide on the touch screen");
return false;
}
# @OVERRIDE
Public Void Olongpress (MotionEvent MotionEvent) {
Log.d (tag, "Online: long press and not loose"); # @Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
Log.d(TAG, "onFling: Slide quickly and release");
return false;
}
}
}
Corresponding operation screenshots:
1. Release immediately after pressing:
2. Press and hold and release:
3. Swipe gently and release at the same time:
4. Press and hold Hold on and continue sliding:
PS: Judging from the above results, we found a problem: When we implement OnGestureListener, we need to implement all gestures. Maybe I am only targeting sliding, but you still have to overload it. This seems very funny, right? The official will definitely provide a solution. The official also provides us with a SimpleOnGestureListener class. Just replace the above OnGestureListener with SimpleOnGestureListener!
3. Simple example: slide down to close the Activity, slide up to start a new Activity
Let’s use the above-mentioned SimpleOnGestureListener to achieve it:
Running rendering:
Implementation code:
private GestureDetector mDetector;
private final static int MIN_MOVE = 200; //Minimum distance
private MyGestureListener mgListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiate SimpleOnGestureListener and GestureDetector objects
mglistener = new myGestureListener ();
MDETECTOR = New Gesturedetector (this, mglistener);
}
# Public Boolean (Motionevent Event) {
Return MDETECTOR .onTouchEvent(event);
}
//Customize a GestureListener, this is under the View class, don’t write it wrong! ! !
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
if(e1.getY() - e2.getY() > MIN_MOVE){
startActivity(new Intent(MainActivity.this, MainActivity.class)); .show(); Activity",Toast.LENGTH_SHORT).show();
}
return true;
}
}
}
Result analysis:As you can see from the above comparison, compared to SimpleOnGestureListener, use SimpleOnGestureListener It seems simpler. You can rewrite whatever method you want. In addition, the example is relatively simple. You can try it yourself. Other ways to play, such as zooming pictures through gestures~
4. Gesture addition and recognition:
In addition to the gesture detection explained above, Android also allows us to add gestures , and then provides relevant identification API; GestureLibrary is used in Android to represent gesture libraries, and the GestureLibraries tool class is provided to create gesture libraries!
Four static methods for loading gesture libraries:
After obtaining the GestureLibraries object, you can use the following methods provided by the object to perform 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) : Obtain all gestures corresponding to the entryName name
- public ArrayList<Prediction> recognize (Gesture gesture): Recognize all gestures matching gesture from the current gesture library
- 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 entryName in the gesture library Gestures that match gesture
- public abstract boolean save (): Call this method to save the gesture library after adding a gesture to or deleting a gesture from the gesture library
GestureOverlayView gesture editing component:
Android provides three listener interfaces for GestureOverlayView, as follows, the commonly used ones are: OnGesturePerformedListener; used when the gesture is completed response!
5. Gesture adding example:
PS: The example refers to the code of Li Gang's "Android Crazy Lecture Notes"
Running renderings:
Okay, here’s the implementation code:
Two layout files: activity_main.xml and dialog_save. xml
activity_main.xml
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 gestures on the screen below~"
android:textSize="20sp"/ >
## ="@+id/gesture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gestureStrokeType="multiple" />
</ LinearLayout>
dialog_save.xml
<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="请填写手势名称:"/>
<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:
private EditText editText;
private GestureOverlayView gesture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取手势编辑组件后,设置相关参数
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) {
View saveDialog = getLayoutInflater().inflate(R.layout.dialog_save,null,false);
ImageView img_show = (ImageView) saveDialog.findViewById(R.id.img_show);
final EditText edit_name = (EditText) saveDialog.findViewById(R.id.edit_name);
Bitmap bitmap = gesture.toBitmap(128,128,10,0xffff0000);
img_show.setImageBitmap(bitmap);
new AlertDialog.Builder(MainActivity.this).setView(saveDialog)
.setPositiveButton("保存",new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//获取文件对应的手势库
GestureLibrary gestureLib = GestureLibraries.fromFile("/mnt/sdcard/mygestures");
gestureLib.addGesture(edit_name.getText().toString(),gesture);
gestureLib.save();
}
}).setNegativeButton("取消", null).show();
}
});
}
}
Finally, you need to add the permission to write to the SD card in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
6. Gesture recognition example
Implementation code:
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, "Gesture library loading failed", Toast.LENGTH_SHORT).show();
Toast. ) findViewById(R.id.gesture);
gesture.setGestureColor(Color.GREEN);
gesture.setGestureStrokeWidth(5);
gesture.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
@ Override
Public Void ONEESTUREPERFORMED (GESTUREOVERLAYVIEW GESTUREOVIEW, FINAL GESTURE GESTURE) {
// Recognize the gesture of the user just drawn
arraylist & ltic Tion & GT; Predictions = GESTURELIBRARY.RCOGNIZE (GESTURE);
ArrayList & LT; String & GT; result = new ArrayList<String>();
for (Prediction pred : predictions) {
);
adapter = new ArrayAdapter<Object>(mContext,
, result.toArray());
Toast. makeText(mContext,"Unable to find matching gesture!",Toast.LENGTH_SHORT).show();
); Don’t forget to add the permission to read the SD card in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Summary of this section: