Android Gesture Recognition and custom gesture

Source: Internet
Author: User

Today, I will introduce some knowledge about gesture and multi-touch ......

First, identify the last dish and gesture .....

java.lang.Object   ↳android.view.View    ↳android.view.ViewGroup     ↳android.widget.FrameLayout      ↳android.gesture.GestureOverlayView

Introduce gestureoverlayview. This transparent view allows you to draw gestures on it and stack it on other views.

There are three other interfaces related to this class:

Gestureoverlayview. ongesturelistener;

Gestureoverlayview. ongesturew.medlistener(Role: identify whether the gesture matches the gesture in the gesture Library Based on the gesture drawn on gestureoverlayview );

Gestureoverlayview. ongesturinglistener.

Introduction to the XML attributes of gestureoverlayview:

Android: gesturestroketype

Set the number of strokes for a gesture. It has two values: gesture_stroke_type_multiple (multiple strokes) and gesture_stroke_type_single (one stroke)

public final class GestureLibraries
 static GestureLibrary fromFile(File path)  static GestureLibrary fromFile(String path)  static GestureLibrary fromPrivateFile(Context context, String name)  static GestureLibrary fromRawResource(Context context, int resourceId)

You want to directly load gestures from SD card or raw resources;

Next we will introduce the gesture recognition function. First we will introduce the Code:

Gestureidentifydemoactivity. xml

Package COM. potato; import Java. util. arraylist; import android. app. activity; import android. gesture. gesture; import android. gesture. gesturelibraries; import android. gesture. gesturelibrary; import android. gesture. gestureoverlayview; import android. gesture. prediction; import android. OS. bundle; import android. widget. toast; public class gestureidentifydemoactivity extends activity {// gesturelibrary mgesturel Ib;/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // gestureoverlayview gestures = (gestureoverlayview) findviewbyid (R. id. gesture_overlay_view_test); // The gestures listener for Gesture Recognition. addongesturew.medlistener (New gestureoverlayview. ongesturesponmedlistener () {// Note 1 @ overridepubli C void ongesturesponmed (gestureoverlayview overlay, gesture) {// query the matched content from the gesture library. The matched results may include multiple similar results, the results with high matching degree are placed at the beginning of arraylist <prediction> predictions = mgesturelib. recognize (gesture); // note 3if (predictions. size ()> 0) {prediction = (prediction) predictions. get (0); // match the gesture if (prediction. score> 1.0) {toast. maketext (gestureidentifydemoactivity. this, prediction. name, toast. length_short ). show () ;}}}); // Load the existing gesture library mgesturelib = gesturelibraries. fromrawresource (this, R. Raw. Gestures) from raw; // note 2if (! Mgesturelib. Load () {finish ();}}}

Note 1:

gestures.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener()

Gesture Recognition listener ....

NOTE 2:

mGestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);

Load the gestures gesture file from Res/raw/

NOTE 3:

ArrayList<Prediction> predictions = mGestureLib.recognize(gesture);

Recognize the gestures drawn in the gestureoverlayview from the gesture library;

Mian. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "input gesture:"/> <! -- Pay attention to Android. gesture. to add, otherwise an error is reported. It is estimated that the package cannot be found --> <android. gesture. gestureoverlayview Android: Id = "@ + ID/gesture_overlay_view_test" Android: layout_width = "match_parent" Android: layout_height = "0dip" Android: layout_weight = "1.0" Android: gesturestroketype = "multiple"/> </linearlayout>

Note: For android. gesture. gestureoverlayview, gestureoverlayview cannot be used.

The following describes how to add custom gestures to the gesture Library:

Code:

Gesturebuilderdemoactivity. Java

Package COM. potato; import Java. io. file; import Java. util. collections; import Java. util. comparator; import Java. util. hashmap; import Java. util. map; import android. app. activity; import android. content. context; import android. content. intent; import android. content. res. resources; import android. gesture. gesture; import android. gesture. gesturelibraries; import android. gesture. gesturelibrary; import android. graphics. Bitmap; import android. graphics. drawable. bitmapdrawable; import android. graphics. drawable. drawable; import android. OS. bundle; import android. OS. environment; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. arrayadapter; import android. widget. button; import android. widget. listview; import android. widget. textview; public class gesturebuilderdemoa Ctivity extends activity {Private Static final int STATUS_SUCCESS = 0; Private Static final int status_cancelled = 1; Private Static final int status_no_storage = 2; Private Static final int status_not_loaded = 3; private Static final int request_new_gesture = 1; // Private final file mstorefile = new file (environment. getexternalstoragedirectory (), "gestures"); Private gesturesadapter madapter; PR Ivate static gesturelibrary mgesturelib; private textview mtvempty; button mbtnaddgesture; button mbtnidentify; resources MREs; listview mlistviewgesture; // width and height private int mthumbnailsize; // density private int limit; // color private int mpathcolor; static gesturelibrary getstore () {return mgesturelib;}/*** gesture sorting */private final comparator <namedgesture> msorter = new comparator <namedgesture> () {public Int compare (namedgesture object1, namedgesture object2) {return object1.name. compareto (object2.name) ;}};/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); MREs = getresources (); mbtnaddgesture = (button) findviewbyid (R. id. addbutton); mbtnidentify = (button) findviewbyid (R. id. reloa Dbutton); mpathcolor = MREs. getcolor (R. color. gesture_color); mthumbnailinset = (INT) MREs. getdimension (R. dimen. gesture_thumbnail_inset); mthumbnailsize = (INT) MREs. getdimension (R. dimen. gesture_thumbnail_size); mlistviewgesture = (listview) findviewbyid (Android. r. id. list); madapter = new gesturesadapter (this); mlistviewgesture. setadapter (madapter); If (mgesturelib = NULL) {mgesturelib = gesturelibraries. Fromfile (mstorefile); // Note 1} mtvempty = (textview) findviewbyid (Android. r. id. empty); loadgestures (); If (mlistviewgesture. getadapter (). isempty () {mlistviewgesture. setemptyview (mtvempty); mbtnaddgesture. setenabled (false);} else {mbtnaddgesture. setenabled (true) ;}@overrideprotected void onactivityresult (INT requestcode, int resultcode, intent data) {super. onactivityresult (requestcode, resultcode, data); If (resultcode = result_ OK) {Switch (requestcode) {Case request_new_gesture: loadgestures (); break ;}}} /*** recognition gesture */@ suppresswarnings ({"unuseddeclaration"}) Public void identifygestures (view v) {intent = new intent (this, gestureidentifydemoactivity. class); startactivity (intent);}/*** create gesture * @ Param v */@ suppresswarnings ({"unuseddeclaration"}) Public void addgesture (view V) {intent = New intent (this, creategestureactivity. Class); startactivityforresult (intent, request_new_gesture);}/*** load gesture * @ return */private int loadgestures () {If (! Environment. media_mounted.equals (environment. getexternalstoragestate () {return status_no_storage;} final gesturelibrary gesturelib = mgesturelib; madapter. clear (); If (gesturelib. load () {// note 2For (string name: gesturelib. getgestureentries () {for (gesture: gesturelib. getgestures (name) {final Bitmap bitmap = gesture. tobitmap (thinkumbnailsize, // Note 3 thinkumbnailsize, thinkumbnailinset, mpathcolor); Final namedgesture = new namedgesture (); namedgesture. gesture = gesture; namedgesture. name = Name; madapter. addbitmap (namedgesture. gesture. GETID (), bitmap); madapter. add (namedgesture) ;}} madapter. sort (msorter); // note 4madapter. notifydatasetchanged (); Return succeeded;} return succeeded;} static class namedgesture {string name; gesture;} private class gesturesadapter extends arrayadapter <namedgesture> {private final layoutinflater minflater; private final map <long, drawable> mthumbnails = collections. synchronizedmap (New hashmap <long, drawable> (); Public gesturesadapter (context) {super (context, 0); minflater = (layoutinflater) context. getsystemservice (context. layout_inflater_service);} void addbitmap (long ID, Bitmap bitmap) {mthumbnails. put (ID, new bitmapdrawable (Bitmap) ;}@ overridepublic view getview (INT position, view convertview, viewgroup parent) {If (convertview = NULL) {convertview = minflater. inflate (R. layout. list_item_gesture, parent, false);} final namedgesture gesture = getitem (position); Final textview label = (textview) convertview; label. settag (gesture); label. settext (gesture. name); label. setcompounddrawableswithintrinsicbounds (mthumbnails. get (gesture. gesture. GETID (), null); Return convertview ;}};}

Note 1

mGestureLib = GestureLibraries.fromFile(mStoreFile);

Load the existing gesture from the SD card;

Note 2

gestureLib.load()

Load a gesture from the gesture Library

Note 3

Final Bitmap bitmap = gesture. tobitmap (thinkumbnailsize, // Note 3 thinkumbnailsize, thinkumbnailinset, mpathcolor );

Convert a gesture to a bitmap

Note 4

Sort

Main. xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="#009966"    android:orientation="vertical" >    <ListView        android:id="@android:id/list"        android:layout_width="fill_parent"        android:layout_height="0dip"        android:layout_weight="1.0" />    <LinearLayout        style="@android:style/ButtonBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:id="@+id/addButton"            android:layout_width="0dip"            android:layout_height="wrap_content"            android:layout_weight="1"            android:enabled="false"            android:onClick="addGesture"            android:text="button_add" />        <Button            android:id="@+id/reloadButton"            android:layout_width="0dip"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="identifyGestures"            android:text="button_identify" />    </LinearLayout></LinearLayout>

Create gesture

Creategestureactivity. Java

Package COM. potato; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. view. view; import android. view. motionevent; import android. gesture. gestureoverlayview; import android. gesture. gesture; import android. gesture. gesturelibrary; import android. widget. textview; import android. widget. toast; import Java. io. file; public class creategestureactivity extends Activity {Private Static final float length_threshold = 1200000f; private gesture mgesture; private view mdonebutton; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. create_gesture); mdonebutton = findviewbyid (R. id. done); gestureoverlayview overlay = (gestureoverlayview) findviewbyid (R. id. gestures_overlay); overlay. addongesturelistener (New GES Turesprocessor () ;}@ overrideprotected void onsaveinstancestate (bundle outstate) {super. onsaveinstancestate (outstate); If (mgesture! = NULL) {outstate. putparcelable ("gesture", mgesture) ;}@ overrideprotected void onrestoreinstancestate (bundle savedinstancestate) {super. onrestoreinstancestate (savedinstancestate); mgesture = savedinstancestate. getparcelable ("gesture"); If (mgesture! = NULL) {final gestureoverlayview overlay = (gestureoverlayview) findviewbyid (R. id. gestures_overlay); overlay. post (New runnable () {public void run () {overlay. setgesture (mgesture) ;}}); mdonebutton. setenabled (true) ;}}/*** add gesture button * @ Param v */Public void addgesture (view v) {If (mgesture! = NULL) {final textview input = (textview) findviewbyid (R. id. gesture_name); Final charsequence name = input. gettext (); If (name. length () = 0) {input. seterror ("enter the name of gesture! "); Return;} // Add the gesture to the gesture library final gesturelibrary store = gesturebuilderdemoactivity. getstore (); // note 1store. addgesture (name. tostring (), mgesture); store. save (); setresult (result_ OK); final string Path = new file (environment. getexternalstoragedirectory (), "gestures "). getabsolutepath (); toast. maketext (this, "saved successfully" + path, toast. length_long ). show ();} else {setresult (result_canceled);} finish ();}/*** cancel gesture * @ Param v */Public void cancelgesture (view V) {setresult (result_canceled); finish () ;}/ *** the gesture listens to * @ author administrator **/private class gesturesprocessor implementsgestureoverlayview. ongesturelistener {public void ongesturestarted (gestureoverlayview overlay, motionevent event) {mdonebutton. setenabled (false); mgesture = NULL;} public void ongesture (gestureoverlayview overlay, motionevent event) {} public void ongestureended (gestureoverlayview overlay, motionevent event) {// obtain the gestureoverlayview gesture mgesture = overlay. getgesture (); // note 2if (mgesture. getlength () <length_threshold) {overlay. clear (false);} mdonebutton. setenabled (true);} public void ongesturecancelled (gestureoverlayview overlay, motionevent event ){}}}

Note 1

Final gesturelibrary store = gesturebuilderdemoactivity. getstore (); // note 1store. addgesture (name. tostring (), mgesture); store. Save ();

Gesture added to gesture Library

Note 2

Get the gestureoverlayview gesture

Create_gesture.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="6dip"            android:text="prompt_gesture_name"            android:textAppearance="?android:attr/textAppearanceMedium" />                <EditText            android:id="@+id/gesture_name"            android:layout_width="0dip"            android:layout_weight="1.0"            android:layout_height="wrap_content"            android:maxLength="40"            android:singleLine="true" />    </LinearLayout>        <android.gesture.GestureOverlayView        android:id="@+id/gestures_overlay"        android:layout_width="match_parent"        android:layout_height="0dip"        android:layout_weight="1.0"        android:gestureStrokeType="multiple" />    <LinearLayout        style="@android:style/ButtonBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:id="@+id/done"            android:layout_width="0dip"            android:layout_height="wrap_content"            android:layout_weight="1"            android:enabled="false"            android:onClick="addGesture"            android:text="button_done" />            <Button            android:layout_width="0dip"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="cancelGesture"            android:text="button_discard" />        </LinearLayout>    </LinearLayout>

Note: Do not forget to add the permission to write to the SD card when writing gestures.

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

If you have any questions, please leave a message or send an email.

Ligexiao@gmail.com

Source code: http://download.csdn.net/detail/alex0203/3868687

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: info-contact@alibabacloud.com 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.