Android開發之Thread+Handler樣本(打地鼠)

來源:互聯網
上載者:User

Android開發之Thread+Handler樣本(打地鼠)
直接上代碼

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; // 記錄其打到了幾隻地鼠private ImageView mouse; // 聲明一個ImageView對象private Handler handler; // 聲明一個Handler對象public int[][] position = new int[][] { { 231, 325 }, { 424, 349 },{ 521, 256 }, { 543, 296 }, { 719, 245 }, { 832, 292 },{ 772, 358 } }; // 建立一個表示地鼠位置的數組@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mouse = (ImageView) findViewById(R.id.imageView1); // 擷取ImageView對象mouse.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {v.setVisibility(View.INVISIBLE); // 設定地鼠不顯示i++;Toast.makeText(MainActivity.this, 打到[  + i +  ]只地鼠!,Toast.LENGTH_SHORT).show(); // 顯示訊息提示框return false;}});handler = new Handler() {@Overridepublic void handleMessage(Message msg) {int index = 0;if (msg.what == 0x101) {index = msg.arg1; // 擷取位置索引值mouse.setX(position[index][0]); // 設定X軸位置mouse.setY(position[index][1]); // 設定Y軸位置mouse.setVisibility(View.VISIBLE); // 設定地鼠顯示}super.handleMessage(msg);}};Thread t = new Thread(new Runnable() {@Overridepublic void run() {int index = 0; // 建立一個記錄地鼠位置的索引值while (!Thread.currentThread().isInterrupted()) {index = new Random().nextInt(position.length); // 產生一個隨機數Message m = handler.obtainMessage(); // 擷取一個Messagem.what = 0x101; // 設定訊息標識m.arg1 = index; // 儲存地滑鼠位置的索引值handler.sendMessage(m); // 發送訊息try {Thread.sleep(new Random().nextInt(500) + 500); // 休眠一段時間} catch (InterruptedException e) {e.printStackTrace();}}}});t.start(); // 開啟線程}}

 

<framelayout android:background="@drawable/background" android:id="@+id/fl" android:layout_height="fill_parent" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">    </framelayout>


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.