首页 > 代码库 > Android Handler之Message传递参数
Android Handler之Message传递参数
最近发现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 = 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:
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); } }
Android Handler之Message传递参数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。