Directly on the code
Package Com.mingrisoft;import Java.util.random;import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.message;import Android.view.motionevent;import Android.view.View;import Android.view.view.ontouchlistener;import Android.widget.imageview;import Android.widget.toast;public Class Mainactivity extends Activity {private int i = 0;//record it hit a few hamsters private ImageView mouse;//Declare a ImageView object private Handler Handler Declares a handler object public int[][] position = new int[][] {{231, 325}, {424, 349},{521, 256}, {543, 296}, {719, 245 }, {832, 292},{772, 358}}; Create an array that represents the location of the Gopher @overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main); mouse = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Gets the ImageView object Mouse.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent Event) {v.setvisibility (view.invisible);//Set the hamster not to show i++; Toast.maketext (Mainactivity.thiS, "Hit to [" + i + "] only gopher! ", Toast.length_short). Show (); Show message prompt box return false;}); Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {int index = 0;if (Msg.what = = 0x101) {index = ms G.ARG1; Gets the positional index value MOUSE.SETX (position[index][0]); Set X-axis position mouse.sety (position[index][1]); Set y-axis position mouse.setvisibility (view.visible); Set the hamster to show}super.handlemessage (msg);}; Thread t = new Thread (new Runnable () {@Overridepublic void run () {int index = 0;//create an index value to record the location of the hamster while (! Thread.CurrentThread (). isinterrupted ()) {index = new random (). Nextint (position.length);//Generate a random number message M = Handler.obtainmessage (); Get a messagem.what = 0x101; Set Message id M.ARG1 = index; The index value of the location of the saved mouse Handler.sendmessage (m); Send Message try {thread.sleep (New Random (). Nextint (500) + 500);//Hibernate for some time} catch (Interruptedexception e) {e.printstacktrace () ;}}}}); T.start (); Open Thread}}
Layout file:
<?xml version= "1.0" encoding= "Utf-8"? ><framelayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/fl " android:background=" @drawable/background " android:layout_width=" fill _parent " android:layout_height=" fill_parent "> <imageview android:id=" @+id/imageview1 " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/mouse" /></framelayout>
Thread+handler Example of Android development (Gopher)