Android中Message传递参数【安卓进化十六】
最近发现Message,发送消息可以传递参数,这个思路很好,所以写了一个例子,点击屏幕,给Activity发送一个消息,传递两个参数,并把这个activity销毁掉!
转载请标明出处:http://blog.csdn.net/wdaming1986/article/details/6748688
程序打开界面: 点击屏幕,销毁activity弹出Toast:
看代码:
MainActivity。java类:
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。java类:
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();
}
www.zzzyk.com
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;
&nbs
补充:移动开发 , Android ,