Handler用Bundle传值

package com.handler.cn;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class main extends Activity {

    private Button myButton01, myButton02;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myButton01 = (Button) findViewById(R.id.Button01);
        myButton02 = (Button) findViewById(R.id.Button02);

        myButton01.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                myHandler.sendEmptyMessage(0);
            }
        });
        
        myButton02.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Message myMessage = new Message();
                myMessage.what = 1;
                Bundle myBundle = new Bundle();
                myBundle.putString("name", "刘馨妍");
                myBundle.putString("number", "1234567890");
                myMessage.setData(myBundle);
                myHandler.sendMessage(myMessage);
            }
        });

    }

    // 创建Handler类的实例
    Handler myHandler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                Toast.makeText(main.this, "结果是:" + msg.what, Toast.LENGTH_LONG)
                        .show();
                break;
            case 1:
                Bundle myBundle1 = msg.getData();
                String myName = myBundle1.getString("name");
                String myNumber = myBundle1.getString("number");
                Toast.makeText(
                        main.this,
                        "姓名:" + myName + " ,号码:" + myNumber + " ,结果是:"
                                + msg.what, Toast.LENGTH_LONG).show();
                break;
            }
        }
    };

}

转载于:https://www.cnblogs.com/androidsj/p/3381559.html

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值