Fragment 跳转到 Activity 如何接收回来的数据

1.在fragment 里跳转

intent=new Intent(getActivity(), ChooseCityActivity.class);
intent.putExtra(Constant.NowCity,locationCity);
getActivity().startActivityForResult(intent,Constant.ChooseCityActivityCode);

****2.另一个activity里接收
定义一个回传数据的intent
一个接收fragement传递数据的intent****

backIntent=new Intent();//回传的Intent
mIntent=getIntent();
currentCity=mIntent.getStringExtra(Constant.NowCity);

定义一个setResult方法
并且在里面传递数据,调用回传

backIntent.putExtra(Constant.ChoosedCity, choosedCity);
// 设置结果,并进行传送
ChooseCityActivity.this.setResult(Constant.ChooseCityActivityResultCode, backIntent);

**3.在 fragment 所在的activity里处理返回结果
本来我是用广播写的数据接收,后面觉得没有必要
注意里面有一行代码是分发到fragment里,一定要加上这行代码,不然fragment里没有回传的数据**

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case Constant.ChooseCityActivityCode:
if (resultCode==Constant.ChooseCityActivityResultCode){
String city=new String();
Log.i(TAG,”data:”+data);
city=data.getStringExtra(Constant.ChoosedCity);
//updateView(city);
//返回首页的时候 替换上次的定位
SharedPreferencesUtils.putShared(MainActivity.this,Constant.LastAdress,city);
mFragment[0].onActivityResult( requestCode, resultCode, data);//分发到Fragment里
//
Log.i(TAG,”city:”+city);
//sendChoosedCityBroadCastReceiver(city);//更新了位置 发送广播
}
break;
}
}

****4.fragment处理回传的数据
重写onActivityResult方法,得到数据,更新UI****

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==Constant.ChooseCityActivityCode&&data!=null){
Bundle bundle=data.getExtras();
if (resultCode==Constant.ChooseCityActivityResultCode){
String city=bundle.getString(Constant.ChoosedCity);
Log.i(TAG,”onActivityResult city=”+city);
updateView(city);
}
}
}

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页