10-bundle浅析

  • Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。
  • 我们经常使用Bundle在Activity之间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。当Bundle传递的是对象或对象数组时,必须实现Serializable 或Parcelable接口。下面分别介绍Activity之间如何传递基本类型、传递对象。

1.在onSaveInstanceState(…)方法里保存数据

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    super. onSaveInstanceState(savedInstanceState);
    Log.i(TAG,'onSaveInstanceState');
    savedInstanceState.putInt(KEY_INDEX,mCurrentIndex);
}

2.在onCreate(…)方法里读取数据

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    ...
    if(savedInstanceState != null){
        mCurrentIndex = savedInstanceState.getInt(KEY_INDEX);
    }
}

3.举例

//调用端: 
Bundle bundle = new Bundle(); 
bundle.putString("sex" , "男人");
bundle.putDouble("height" , 40,38);
Intent intent = new Intent(); 
intent.putExtras(bundle); 
intent.setClass(ThisOne.this , ThatOne.class);
startActivity(intent);   
//接收端:
 Bundle bundle = this.getIntent().getExtras();
 String sex = bundle.getString("sex"); 
double height = bundle.getDouble("height"); 

参考资料:
http://developer.android.com/reference/android/os/Bundle.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值