Android中Handler類的簡單使用,實現圖片切換
阿新 • • 發佈:2019-02-01
Handler類主要有兩個作用:在新啟動的執行緒中傳送訊息。在主執行緒中獲取、處理訊息。當新啟動的執行緒傳送訊息時,Handler類中處理訊息的方法會被自動回撥。Handler類包含如下方法用於傳送、處理訊息:
下面通過一個簡單例項來演示Handler的使用,實現點選切換按鈕,圖片開始自動切換;點選停止按鈕,圖片停止切換,程式碼如下:
Activity:
package com.lovo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class ChangeImageActivity extends Activity { // 宣告Handler物件 private Handler handler; // 切換顯示圖片陣列id的下標 private int index; // 切換是否進行 private boolean isRun = true; public static final int CHANGE_IMAGE = 1; // 切換的圖片id陣列 private int[] images = new int[] { R.drawable.whatsnew_fornew_01, R.drawable.whatsnew_fornew_02, R.drawable.whatsnew_fornew_03, R.drawable.whatsnew_fornew_04, R.drawable.whatsnew_fornew_05 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == CHANGE_IMAGE) { ImageView imageView = (ImageView) findViewById(R.id.image); // 動態改變ImageView裡面的圖片 imageView.setImageResource(images[msg.getData().getInt( "index")]); } } }; // 獲得按鈕 Button btn1 = (Button) findViewById(R.id.btn1); Button btn2 = (Button) findViewById(R.id.btn2); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { isRun = false; } }); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { isRun = true; new Thread() { public void run() { for (index = 0; isRun; index++) { Message msg = new Message(); msg.what = CHANGE_IMAGE; // 建立Bundle物件,封裝資料 Bundle bundle = new Bundle(); bundle.putInt("index", index); msg.setData(bundle); // 傳送訊息 handler.sendMessage(msg); // 迴圈切換 if (index >= 4) { index = -1; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } }); } }
佈局XML:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切換" /> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/btn1" android:text="停止" /> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/btn1" /> </RelativeLayout>