文章图片
传回数据给CrimeFragment
实现activity的数据回传,是通过ActivityManager负责跟踪管理父activity和子activity间的关系。
回传数据后子activity被销毁,但ActivityManager知道接收数据的是哪个activity
类比这个,可以将CrimeFragment作为DatePickerFragment回传数据的目标Fragment,即使CF与DPF被销毁和重建后,操作系统也会重新关联它们
FragmentManager manager=getFragmentManager();
DatePickerFragment dialog=DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this,REQUEST_DATE);
dialog.show(manager,DIALOG_DATE);
public void setTargetFragment(Fragment fragment,int requestCode)
在DatePickerFragment中可以通过getTargetFragment()和getTargetRequestCode()来获取这两个参数
目标fragment和请求代码由FragmentManager负责跟踪管理
从子activity退回到父activity时,父activity接收到调用Activity.onActivityResult方法的指令,其FragmentManager会调用对应fragment的FragmentManager
这下不是从activity退回activity,是从fragment退回fragment,就没有上面哪个机制,所以采用在DatePickerFragment里自行调用CrimeFragment的onActivitsetult
private void sendResult(int resultCode,Date date){
if(getTargetFragment()==null)
return;
Intent intent=new Intent();
intent.putExtra(EXTRA_DATE,date);
getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
}
重写对话框positive按钮监听器的代码
并在这其中获取用户设定的日期值,并调用sendResult将值返回给CrimeFragment
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year=mDatePicker.getYear();
int month=mDatePicker.getMonth();
int day=mDatePicker.getDayOfMonth();
Date date=new GregorianCalendar(year,month,day).getTime();
sendResult(Activity.RESULT_OK,date);
}
})
【从DialogFragment回传数据给CrimeFragment】实现Crime Fragment的onActivityResult
取出回传的数据
@Override
public void onActivityResult(int requestCode,int resultCode,Intent intent){if(resultCode!=Activity.RESULT_OK)
return;
if(requestCode==REQUEST_DATE){
Date date=(Date)intent.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}