如何在Bundle间传递ArrayList<Integer>及在生命周期方法间传递指定数据?
解决方案:两个Android数据传递问题拆解
一、在Bundle之间传递ArrayList
ArrayList<Integer>本身实现了Serializable接口,Android的Bundle提供了直接支持这类集合的API,不用额外处理序列化,非常简单:
发送方(比如当前Activity/Fragment)
// 准备要传递的ArrayList ArrayList<Integer> numList = new ArrayList<>(); numList.add(10); numList.add(20); numList.add(30); // 存入Bundle Bundle bundle = new Bundle(); // 用专门的putIntegerArrayList方法,比putSerializable更直观 bundle.putIntegerArrayList("INT_LIST_KEY", numList); // 如果你是用Intent跳转Activity,把bundle附到Intent里 Intent intent = new Intent(this, TargetActivity.class); intent.putExtras(bundle); startActivity(intent); // 如果是Fragment之间传递,直接把bundle传给Fragment的setArguments() TargetFragment fragment = new TargetFragment(); fragment.setArguments(bundle);
接收方(目标Activity/Fragment)
// Activity中接收 Bundle bundle = getIntent().getExtras(); if (bundle != null) { ArrayList<Integer> receivedList = bundle.getIntegerArrayList("INT_LIST_KEY"); if (receivedList != null) { // 这里处理接收到的集合 Log.d("TAG", "Received list: " + receivedList.toString()); } } // Fragment中接收 Bundle bundle = getArguments(); if (bundle != null) { ArrayList<Integer> receivedList = bundle.getIntegerArrayList("INT_LIST_KEY"); // 后续处理... }
注意:如果是自定义对象的ArrayList,需要让对象实现
Parcelable接口,但Integer是系统类,已经支持,直接用上面的方法就好。
二、通过onSaveInstanceState传递_selectednumber和_points
当Activity因系统回收或配置变化(比如旋转)重建时,onSaveInstanceState会帮我们暂存数据,之后在onRestoreInstanceState或onCreate中恢复,步骤如下:
1. 重写onSaveInstanceState保存数据
// 假设_selectednumber是int类型,_points是ArrayList<Integer>类型 @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // 保存单个整数 outState.putInt("SELECTED_NUM_KEY", _selectednumber); // 保存ArrayList<Integer>,同样用putIntegerArrayList outState.putIntegerArrayList("POINTS_LIST_KEY", _points); }
2. 在onRestoreInstanceState中恢复数据
@Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // 恢复_selectednumber,第二个参数是默认值,如果Bundle中没有这个key就用它 _selectednumber = savedInstanceState.getInt("SELECTED_NUM_KEY", 0); // 恢复_points,记得判空避免空指针 _points = savedInstanceState.getIntegerArrayList("POINTS_LIST_KEY"); if (_points == null) { // 如果之前没初始化过,这里新建一个空集合 _points = new ArrayList<>(); } // 恢复数据后可以更新UI,比如刷新列表或文本 updateUI(); }
补充:也可以在onCreate中恢复
如果不想单独重写onRestoreInstanceState,也可以在onCreate里处理:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { _selectednumber = savedInstanceState.getInt("SELECTED_NUM_KEY", 0); _points = savedInstanceState.getIntegerArrayList("POINTS_LIST_KEY"); if (_points == null) { _points = new ArrayList<>(); } } }
注意:
onSaveInstanceState只在系统即将销毁Activity时调用,主动finish的话不会触发,这点要区分开。
内容的提问来源于stack exchange,提问作者HelloWorld1
相关产品推荐
相关产品推荐

