Intent和Bundle传输数据

 

  1. 分别使用Intent和Bundle实现组件间的数据传递。
  • Intent

FirstActivity

Intent( , )第一个参数代表启动活动的上下文,第二个参数指定想要启动的目标活动。startActivity();用于启动活动,将构建好的Intent传入startActivity()方法就可以启动目标活动。通过intent.putExtra( , )方法传递一个字符串,第一个参数相当于名,第二个参数才是真正要传输的数据。

button.setOnClickListener(new View.OnClickListener() {//生成监听器并绑定监听器
     @Override
    public void onClick(View view) {
                     Intent intent = new Intent(Main2Activity.this,Second.class);
               intent.putExtra("com.example.alvin.myapplication2.name", "Tom");

      //数据传递

 startActivity(intent);//启动活动
     }
});

SecondActivity

通过getintent()方法获取到用于启动SecondActivity的Intent,然后调用

getStringExtra()方法传入相应的名字,就可以得到相应数据了,如果传递的

是整型则用getIntExtra()方法。text.setText(str);用于接收并显示str的

值。

text = (TextView)findViewById(R.id.textView);
Intent intent = getIntent();
String str = intent.getStringExtra("com.example.alvin.myapplication2.name");

//取出数据
text.setText(str);

 

 

  • Bundle

FirstActivity

Intent( , )第一个参数代表启动活动的上下文,第二个参数指定想要启动的目标活动。startActivity();用于启动活动,将构建好的Intent传入startActivity()方法就可以启动目标活动。通过bundle.putString( , )方法传递一个字符串。通过bundle.putInt( , )方法传递一个整型数。Inten.putExtras(bundle)用于传bundle中所有的数据。

button.setOnClickListener(new View.OnClickListener() {//生成监听器并绑定监听器
     @Override
     public void onClick(View view) {
               Intent intent = new Intent(Main2Activity.this,Second.class);

     Bundle bundle = new Bundle();
            bundle.putString("name","John");
             bundle.putInt("age", 30);
             intent.putExtras(bundle);//数据传递
              startActivity(intent);
         }
});

SecondActivity

通过intent.getExtras()方法获得bundle所有属性。通过getString("name")

getInt("age")就可以得到相应数据了,text.setText(name+age)用于接收并显示

他们的值。

Bundle bundle = intent.getExtras();
String name = bundle.getString("name");
int age = bundle.getInt("age");
text.setText(name +" "+ age);

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值