最近發現Message,發送消息能夠傳遞參數,這個思路很好,因此寫了一個例子,點擊屏幕,給Activity發送一個消息,傳遞兩個參數,並把這個activity銷燬掉!android
程序打開界面:canvas
點擊屏幕,銷燬activity彈出Toast:app
MainActivity:ide
package com.cn.Android; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Toast; public class MainActivity extends Activity { final static int CANSHU = 1; public Handler mHandler=new Handler(){ public void handleMessage(Message msg) { switch(msg.what){ case CANSHU : String str1 = msg.getData().getString("text1");//接受msg傳遞過來的參數 String str2 = msg.getData().getString("text2");//接受msg傳遞過來的參數 initFinishMainActivity(str1, str2); break; default: break; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); InitMainActivity(); } public void InitMainActivity() { setContentView(new MainActivityView(this,this)); } public void initFinishMainActivity(String str1, String str2) { Toast.makeText(MainActivity.this, str1+str2, Toast.LENGTH_LONG).show(); finish(); } }
MainActivityView:this
package com.cn.android; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; import android.os.Message; import android.view.MotionEvent; import android.view.View; public class MainActivityView extends View{ private MainActivity activity; private Context context; private Bitmap m_Bitmap; public MainActivityView(Context context, MainActivity activity) { super(context); this.activity = activity; this.context = context; initBitmap(); } public void initBitmap() { m_Bitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.bg); } @Override public void onDraw(Canvas canvas) { canvas.drawBitmap(m_Bitmap, 0, 0, null); } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); Rect rect; rect = new Rect(0,0,320,480); if(rect.contains(x,y)) { Message msg = new Message(); msg.what = MainActivity.CANSHU; Bundle bundle = new Bundle(); bundle.putString("text1","大明的消息傳遞參數的例子!"); //往Bundle中存放數據 bundle.putString("text2","Time:2011-09-05"); //往Bundle中put數據 msg.setData(bundle);//mes利用Bundle傳遞數據 activity.mHandler.sendMessage(msg);//用activity中的handler發送消息 } return super.onTouchEvent(event); } }