最近发现Message,发送消息可以传递参数,这个思路很好,所以写了一个例子,点击屏幕,给Activity发送一个消息,传递两个参数,并把这个activity销毁掉!
程序打开界面:
点击屏幕,销毁activity弹出Toast:
MainActivity:
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 = ; 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:
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, , , null); } @Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
Rect rect;
rect = new Rect(,,,); 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);
} }