Android Game Development Custom gesture--Input method gesture technology _android

Source: Internet
Author: User
Tags compact gettext

When it comes to software development, we usually like to use newer versions of the tools, but why do I use a lower version of the SDK to develop the Android game? Here are the reasons:

1, the Android SDK belongs to backward compatibility! So the lower version can be run, the high version is basically no problem! (Of course, every time the SDK updates will bring new features, or modify some of the original bugs, and so on, so in fact, for game development, if your game does not require a higher version of the SDK support, there is no need to pursue the latest sdk! )

2, the use of low version of the game development so that can take into account more models, access to more users!

3, everyone knows that every version of the Android SDK update, the underlying code will be more robust and optimized! For example, our company's online games Android version in G2 (SDK1.5) on the run up a little card, and on my mobile phone (SDK2.2) run up a smooth not to say ~ a variety of comfortable ~ ~ But this will also bring some drawbacks, such as our own game if up on the development of a high version SDK, So for performance, memory in the end, we will not be very easy to see its effect, if we use the lower version of the SDK will let us obviously feel the performance of the end ~ you think if your game on the 1.5, 1.6 running up very smooth, it is on the newer SDK machine is not to mention it ~

Summary: In game development, if your game does not require a higher API support, then the recommendation is based on SDK 1.5 and 1.6来 development!

In the last article I introduced to you the touch screen gesture operation, but this touch-screen gesture has limitations; For example, we all know that Android can use gestures to unlock, like nine Sudoku, through a custom one-stroke gesture can unlock the screen lock, and can customize the stroke gesture to start an application, etc. , then this so-called stroke gesture is actually today I want to explain the input method gesture recognition technology! This gesture is something we can customize, unlike the previous touch-screen gesture that uses Android to encapsulate some touch-screen actions. Here are a few screenshots of the phone's custom strokes to unlock:

OK, so since the use of gestures can be unlocked and other operations, then we play in the development, it is possible to join the bright spot, such as in the game I draw a circle to perform a change of background operation, draw an X to exit the game and so on, and so on, haha is it interesting? OK, let's go to the explanation below!

First of all, this article mainly studies two points:

1. How to create Input method gesture, delete input method gesture, read out gesture file from SD card!

2, when the input method gesture is created, how to match out our custom gestures!

Let's familiarize ourselves with two classes and a few concepts:

1, what is Gestureoverlayview? to put it simply, it is actually a handwritten plot area;

2, what is Gesturelibrary? This class is for gestures to save, delete, and so on, a small warehouse holding gestures!

3. What is the stroke, the font strokes? Yes, it's actually a concept with the pen we write with!

4, what is the type of stroke? in the input method gesture operation, there are two types of strokes, one is: a single stroke, the other is: multiple strokes

A single stroke is a stroke that draws a gesture, from the touch of your finger to the screen and from the moment you leave the screen to form a gesture! Coherent!

and multiple strokes can be a certain amount of time within a few random strokes can be, and then more than this compact time will form a gesture!

First out of the project screenshot, simply say its function and operation:

Figure 1 The interface is divided into 3, from top to bottom is: TextView, Edittext,surfaceview; Then there is a gestureoverlayview! that covers the full screen behind Surfaceview.

Figure 2 Interface is to create a good gesture in the interface to match gestures, it is very clear to see, looking very good ~ Hey ~

First look at the Main.xml:

xml/html Code

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "" Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <textview android:id= "@+id/himi_tv" android:layout_width= fill_parent "android:layout_height=" wrap_content "Android:text=" @string/hello "android:textsize=" 15sp "android:textcolor=" #FFFFFF00 "/> <edittext  = "@+id/himi_edit" android:layout_width= "fill_parent" android:layout_height= "wrap_content"/> <RelativeLayout Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_weight= "1" > <com.h Imi. Mysurfaceview android:id= "@+id/view3d" android:layout_width= "fill_parent" android:layout_height= "Fill_parent"/&gt 
    ; <android.gesture.gestureoverlayview android:id= "@+id/himi_gesture" android:layout_width= "Fill_parent" and Roid:layout_height= "Fill_parEnt "android:layout_weight=" 1.0 "/> </RelativeLayout> </LinearLayout> 

XML registered with our custom Surfaceview, not too familiar with the Android game to see the development of 6, not much explanation. About Gestureoverlayview Here is also simply defined by the wide-height, there are some important property settings in the code set, of course, XML can also be set.

Look below

Java code

/** * @author Himi *@ Input Method gesture Recognition *@ Note: Android.gesture This class in Api-4 (SDK1.6) only began to support! 
 *@ Reminder: Default to the SD card, so don't forget to add SD card read and Write permission in Androidmainfest.xml! * * Public class Mainactivity extends activity {Private Gestureoverlayview gov;//create a handwriting plot area private gesture Gestu  
  re;//Handwriting Instance Private Gesturelibrary gesturelib;//Create a gesture warehouse private TextView TV;  
  Private EditText et;  
    Private String path;//gesture file path private file file;//@Override public void onCreate (Bundle savedinstancestate) {  
    Super.oncreate (savedinstancestate); This.getwindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREE  
    This.requestwindowfeature (Window.feature_no_title);  
    Setcontentview (R.layout.main);  
    TV = (TextView) Findviewbyid (R.ID.HIMI_TV);  
    ET = (edittext) Findviewbyid (;  
    gov = (Gestureoverlayview) Findviewbyid (; Gov.setgesturestroketype (Gestureoverlayview.gesture_stroke_type_muLtiple)//Set Stroke type//gestureoverlayview.gesture_stroke_type_multiple setting supports multiple strokes//Gestureoverlayview.gesture_stro  
    Ke_type_single only supports a single stroke path = new File (Environment.getexternalstoragedirectory (), "gestures"). GetAbsolutePath (); Get the default path and filename/sdcard/gestures file = new files (path);//Instance gestures object Gesturelib = Gesturelibraries.fromfil E (path);//Instance Gesture warehouse Gov.addongesturelistener (new Ongesturelistener () {//This is the bound handwriting plot area @Override/  
            /The following method triggers the public void ongesturestarted (Gestureoverlayview overlay, motionevent event) When you start to draw gestures { Tv.settext ("Please use two strokes to complete a gesture in a tight time!")  
          CC ~ ");  @Override//The following method triggers the public void ongestureended (Gestureoverlayview overlay When the gesture is fully formed, Motionevent event) {gesture = Overlay.getgesture ();//gestures from the plot area if (Gesture.getstrokescoun T () = = 2) {//I decide when the user used two strokes//(emphasis: If the first set of gesture strokes type is a single stroke, then you always get only 1!)!  
          )    if (event.getaction () = = motionevent.action_up) {//Decision two stroke leave screen//if (Gesture.getlength () ==100) {}//Here is a sentence The fixed length reaches 100 pixels if (Et.gettext (). toString (). Equals ("")) {Tv.settext ("because you did not enter a gesture name, so~ save failed  
                ~ ");  
                  else {tv.settext ("Saving gesture ...");  
              Addgesture (Et.gettext (). ToString (), gesture);//I write myself add gesture function}}} else { Tv.settext ("Please use two strokes to complete a gesture in a tight time!")  
            CC ~ "); @Override public void ongesturecancelled (Gestureoverlayview overlay, motionevent EV  ENT) {} @Override public void Ongesture (Gestureoverlayview overlay, motionevent event)  
        }); ----Here is to traverse all gestures at the start of the program!------if (!gesturelib.load ()) {Tv.settext ("Himi hint: gesture more than 9) I did the removal of all gestures, for the interface neat some! "+" Input Method gesture Practice ~ (*^__^*) ~ Hee! /n Operation Introduction: (Draw gestures I set must draw two strokes to do oh ~)/n1."+" Add gestures: First enter the name in the EditText, then draw a gesture on the screen! /n2. Matching gestures: "+" in EditText input/"himi/", and then enter gestures!  
      else {set<string> Set = gesturelib.getgestureentries ();//Remove all gesture Object ob[] = Set.toarray ();  
    Loadallgesture (set, OB); 

This is mainactivity main code, which adds gestures, matching gestures, traversing gestures, turning gestures into pictures I have written a function , so that the children's shoes clearer ideas.

From the above code we see that before the gesture is created, the handwritten plot area (Gestureoverlayview) must first be created, and then we can make strokes in its area, and of course we need to set the stroke type before we draw the gesture, which is what I started to introduce to you, Then the most important thing is the hand-gesture listener bindings in the handwriting plot area, adding Ongesturelistener this listener resets four functions, the most important of which is two functions:

ongesturestarted and ongestureended: A listener function that starts the gesture and ends the gesture.

In particular, gestures to end the listening function is particularly important, in which I set several conditional statements, so a few conditions on the one hand to let everyone understand gesture some of the more important commonly used methods, on the other hand, I would like to remind you children's shoes:

If you set the stroke type to be a multiple stroke type, ideally, it should be within a compact period of time, no matter how many strokes you use to draw gestures, the system should be able to determine that you do not have a stroke in a short period of time should create gestures, and the system responds to this function;

Actually wrong, at first I think so, but found that regardless of whether you set the type of stroke is single or multiple strokes when your finger leaves the screen, regardless of your current number of strokes, Android will respond to this completion function, so~ Here I call the Getstrokescount () function in the gesture gesture class, which records the number of strokes you draw in a compact time, so that we can solve the problem of the finger leaving the screen, because the single stroke type will never be greater than 1!

And if (event.getaction () = = motionevent.action_up) {} Write this just to show you the second parameter key action how to use.

So let's look at how to create a gesture here:

Java code

public void Addmygesture (String name, gesture gesture) {try {if (name.equals ("Himi")) {Findges  
      Ture (gesture);  else {//the sdcard in the two ways to create the simulator is in the "Android2d game development Ten" there is an explanation if (environment.getexternalstoragestate ()!= null)  
          {//This method in the test terminal whether there are sdcard! if (!file.exists ()) {//If there is already a gesture file//No file exists, we go directly to our gesture file in Gesturelib.addgesture (name, GE  
            Sture); if ( ()) {////is saved to the file Gov.clear (true);//clear strokes//Note the saved path defaults to/sdcard/gesture, so  
              ~ Don't forget androidmainfest.xml plus read and Write permission! Here complain, cough, actually yesterday should out this blog, is because here is always unusual, today carefully read//only found not write permission, but I wrote in the Androidmainfest.xml permission, but write the wrong location.  
              Cry to death! Tv.settext ("Save gesture success!") Because there is no gesture file, "+" so the first time to save the gesture success will be the default first create "+" built a gesture file!  
              Then save the gesture to the file. ");  
              Et.settext ("");  
            Gesturetoimage (gesture); else {Tv.settext ("Save gesture failed!")  
            ");} else {//When this file is present we need to remove this gesture and then put the new gesture on//read the existing file to get all the gestures in the file if (!gesturelib.lo AD ()) {//if Read failed Tv.settext ("Gesture file read failed!")  
            ");  else {//read successfully set<string> Set = gesturelib.getgestureentries ()//Fetch all gesture Object ob[]  
              = Set.toarray ();  
              Boolean ishavedgesture = false; for (int i = 0; i < ob.length i++) {//This is the name if (((String) ob[i]) that iterates through all gestures. Equals (name) {//And our new gesture n  
                Ame do contrast ishavedgesture = true; } if (ishavedgesture) {//If this variable is true to indicate a gesture with the same name//----NOTE 1-------------------//gesturel  
                Ib.removegesture (name, gesture);//Delete the gesture with the current name/*----NOTE 2-----------------*/gesturelib.removeentry (name);  
              Gesturelib.addgesture (name, gesture);  
              else {gesturelib.addgesture (name, gesture); } if ( ()) {gov.clear (true);//clear Stroke gesturetoimage (gesture); Tv.settext ("Save gesture success!")  
                At present all gestures have altogether: "+ Ob.length +" ");  
              Et.settext (""); else {Tv.settext ("Save gesture failed!")  
              ");  ////---------The following code clears all operations when more than 9 gestures are--------if (Ob.length > 9) {for (int i = 0; i < ob.length; i++)  
                {//Here is traversal deletion gesture gesturelib.removeentry ((String) ob[i]);  
                } ();  
                if (mysurfaceview.vec_bmp!= null) {MySurfaceView.vec_bmp.removeAllElements ();//Remove the container where the gesture map is placed  
                Tv.settext ("More than 9 gestures, all emptied!");  
              Et.settext ("");  
              OB = NULL;  
            set = NULL; }} else {Tv.settext ("The current emulator does not have an SD card--.  
        "); Catch in}}} (Exception e) {Tv.settext (Operation exception!)  

It is also well understood that the routines similar to the previous file storage routines, first determine whether the SD exists, and then whether the file exists:

If the file does not exist, add it directly to the gesture warehouse, then the gesture store calls () to save gestures to the SD card's gesture file.

The existence of the document also to determine whether the file contains the same name of the gesture, of course, here can not determine whether there is the same gesture name exists, and then delete the operation! In fact, you can not delete, add directly to the current new gesture;

Remark 1: Because Gesturelib's saved gesture is a hashmap, key= gesture's name, value= gesture, so Gesturelib.removegesture (name, gesture); This deletion simply deletes the gesture, the gesture name is still kept in HashMap, and the next time the same name gesture is deposited, HashMap directly overwrites the entry. So according to the characteristics of hashmap, we can not delete operations, can be directly gesturelib.addgesture (name, gesture), because if the same gesture name gesture, HashMap will directly overwrite the value (gesture) of its entry according to key (the name of the gesture) ~

NOTE 2: This is also a way to remove gestures, but this is different from Note 1, where you delete the entries in the HashMap, which means that key and value are deleted!

Here's how to turn the gesture into a bitmap:

Java code

public void Gesturetoimage (gesture Ges) {//convert gesture to bitmap  
   //turn gesture into a picture, save it to the image container defined in our Surfaceview, and then draw the ~  
   if ( Mysurfaceview.vec_bmp!= null) {  
     MySurfaceView.vec_bmp.addElement (ges.tobitmap (MB,;  

Here's how to traverse gestures:

Java code

public void Loadallgesture (set<string> Set, Object ob[]) {//traverse all gestures  
    if (gesturelib.load ()) {//Read the latest gesture file  
      Set = Gesturelib.getgestureentries ();//Remove all gestures  
      OB = Set.toarray ();  
      for (int i = 0; i < ob.length i++) {  
        //turn gesture to bitmap  
        gesturetoimage (((String) gesturelib.getgestures)). Get (0));  
        Here is the name of each of our gestures also saved  
        MySurfaceView.vec_string.addElement ((String) ob[i]);}}  

Here's a final look at the gesture matching:

Java Code

The public void findgesture (gesture gesture) {try {//SDcard on two ways to create the simulator is in the "Android2d Game development X" for a detailed explanation if (environme  
      Nt.getexternalstoragestate ()!= null) {//This method in the test terminal whether there are sdcard! if (!file.exists ()) {//Determine if a gesture file already exists Tv.settext ("match gesture failed because the gesture file does not exist!!")  
          else {//When this file is present we need to remove this gesture and then put the new gesture on//read the existing file, get all gestures if (!gesturelib.load ()) {//if Read fails Tv.settext ("match gesture failed, gesture file read failed!")  
          else {//read successfully list<prediction> predictions = gesturelib.recognize (gesture);  
          The return result of the recognize () is a prediction collection that contains all the results that match the gesture. Query the matching content from the gesture library, matching results may include multiple similar results, if (!predictions.isempty ()) {Prediction prediction = Predictio  
            Ns.get (0); The score attribute of the prediction represents the similarity to the gesture//prediction the name of the symbol//prediction the score attribute representing the similarity to the gesture  
            degree (usually without considering the result of score less than 1). if (Prediction.score >= 1) {tv.seTtext ("Currently your gesture finds the most similar gesture in the gesture library: name =" +; else {Tv.settext ("match gesture failed, the current emulator does not have an SD card--.  
    } catch (Exception e) {e.printstacktrace ();  
  Tv.settext ("Due to abnormal, matching gestures failed ~"); 

Then finally to the children's shoes to say, in fact, the input method gesture operation is very suitable for the use of the game, whether it is touch-screen gesture operation or today, the input method gesture operation if added to the game that is quite a praise!

The above is the implementation of the Android custom gestures example, follow-up to continue to collate relevant information, thank you for your support for this site!

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: 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.