android bundle存放数据详解,activity与activity之间数据传递,fragment与fragment之间数据传递

来源:互联网 发布:全知之眼漫画 编辑:程序博客网 时间:2024/05/14 17:35


1、正如大家所知道,Activity之间传递数据,是将数据存放在Intent或者Bundle中

例如:将数据存放倒Intent中传递:

将数据放到Bundle中传递:

但是Intent或者Bundle存放的数据类型是有限的

我想大家都遇到过这个问题,无法将Map、List<Map<String,Object>>等类型数据存放到Bundle或者Intent中

但是大家是否注意到,Bundle或者Intent允许存放对象数据

我们可以从这点着手,我们只要将需要存放到数据先存到一个对象中,再将这个对象存放到Bundle或者Intent中,我们就能成功将想传递到数据传递过去

 

操作步骤:

新建一个类

 

将数据存放到对象中,再将对象放到Bundle中进行传递

 

Intent intent = new Intent(MainActivity.this,SecondActivity.class);Bundle bundle = new Bundle();Map<String,Objects> map = new HashMap<String,Objects>();map.put("wenhou","你好");map.put("name", "jason");map.put("age", 25);Data data = new Data();data.setMap(map);bundle.putSerializable("data",data);intent.putExtras(bundle);startActivity(intent);
2、Fragment之间数据也可通过bundle进行传递
CourseFragmentOne fragment = new CourseFragmentOne(COURSE_CLASS);FragmentTransaction transaction = getFragmentManager().beginTransaction();//通过bundle对象向Fragment传值Bundle bundle = new Bundle();
bundle.putString("num", CourseLibraryFirstClassBean.getCourse_Num()[childPosition]);fragment.setArguments(bundle);transaction.replace(R.id.fl_course_one, fragment);transaction.commit();
在另一个Fragment处使用
String num = (String) getArguments().get("num");
来接收数据
3、可以通过EventBus来传递数据,在一个Activity使用EventBus发送数据语句:
EventBus.getDefault().post(value);
然后在另外一个activity或fragment中重写onEvent方法,接收EventBus发出的数据
@Subscribepublic void onEvent(String data) {    Log.i(TAG, "onEvent: " + data);}
在接收的fragment中的onCreateView方法中注册EventBus:
EventBus.getDefault().register(this);
在onDestroy方法中解绑EventBus:
EventBus.getDefault().unregister(this);
上述onEvent中拿到的data参数就是上一fragment或avtivity发送的数据,然后对数据进行处理就可以了
                                             
0 0
原创粉丝点击