android通信机制4:Activity与Activity之间的转跳

本文介绍了Android应用开发中Activity间的转跳及数据传递方法。详细讲述了如何使用Intent和Bundle进行数据传递,并给出了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4.Activity与Activity之间的转跳

在软件应用的开发中肯定会有多个Activity     这样它们之间就会存在相互转跳的关系      转跳的实现方式还是使用Intent  然后startActivity  ,当然转跳的话是可以带数据过去的。比如从A跳到B 可以把A中的一些数据通过Intent传递给B 。
读下面这段代码 大家会发现intent与bandle 传递数值的方式基本一样为什么还要分成两个呢? 确实他们两个传递的数值的方式非常类似, 他们两个的区别就是Intent属于把零散的数据传递过去 而bundle则是把零散的数据先放入bundle 然后在传递过去。我举一个例子 比如我们现在有3个activity  A.B.C  须要把A的数据穿给B然后在穿给C ,如果使用intent一个一个传递 须要在A类中一个一个传递给B 然后B类中获取到所有数值  然后在一个一个传递给C  这样很麻烦 但是 如果是bundle的话 B类中直接将bundler传递给C 不用一个一个获得具体的值  然后在C类中直接取得解析数值。

传递
view plain
       /**Activity之间传递值**/  
       Button botton3 = (Button)findViewById(R.id.button3);  
       botton3.setOnClickListener(new OnClickListener() {  
      
    @Override  
    public void onClick(View arg0) {  
     Intent intent = new Intent(mContext,ShowActivity.class);   
     //使用intent.putExtra()直接传递  
     intent.putExtra("name", "雨松MOMO");  
     intent.putExtra("age", 25);  
     intent.putExtra("boy", true);  
      
     //把数值放进bundle 然后在把整个bundle通过intent.putExtra()传递  
     Bundle bundle = new Bundle();  
     bundle.putString("b_name", "小可爱");  
     bundle.putInt("b_age", 23);  
     bundle.putBoolean("b_boy", false);  
     //在这里把整个bundle 放进intent中  
     intent.putExtras(bundle);  
     //开启一个新的 activity 将intent传递过去  
     startActivity(intent);  
    }  
});     

接收
view plain
public class ShowActivity extends Activity {  
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
    setContentView(R.layout.my);  
      
    Intent intent = getIntent();  
      
    String name = intent.getStringExtra("name");  
    //第二个参数为默认值 意思就是如果在intent中拿不到的话  
    //就用默认值  
    int age  = intent.getIntExtra("age", 0);  
    boolean isboy = intent.getBooleanExtra("boy", false);  
    TextView textView0 = (TextView)findViewById(R.id.text0);  
      
    textView0.setText("姓名  " + name + "年龄 " + age + "男孩?  " + isboy);  
      
      
    Bundle bundle = intent.getExtras();  
    name = bundle.getString("b_name");  
    //第二个参数为默认值 意思就是如果在bundle中拿不到的话  
    //就用默认值  
    age = bundle.getInt("b_age",0);  
    isboy = bundle.getBoolean("b_boy", false);  
      
    TextView textView1 = (TextView)findViewById(R.id.text1);  
      
    textView1.setText("姓名  " + name + "年龄 " + age + "男孩?  " + isboy);  
      
    super.onCreate(savedInstanceState);  
    }  
  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值