一、创建对话框
public class DatePickerFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(this.getActivity());
builder.setTitle(R.string.crime_date_picker_title);
builder.setPositiveButton(android.R.string.ok,null);
returnbuilder.create();
}
}
对话框有三种按钮:positive按钮、negative按钮以及neutral按钮。
二、启动对话框
this.mDateButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
FragmentManager manager=CrimeFragment.this.getActivity().getSupportFragmentManager();
DatePickerFragment dialog=new DatePickerFragment();
dialog.show(manager,CrimeFragment.DIALOG_DATE);
}
});
三、给对话框配布局文件
1)、先定义布局文件;
2)、再如下:
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v=this.getActivity().getLayoutInflater().inflate(R.layout.dialog_date,null);
AlertDialog.Builder builder=new AlertDialog.Builder(this.getActivity());
builder.setView(v);
builder.setTitle(R.string.crime_date_picker_title);
builder.setPositiveButton(android.R.string.ok,null);
return builder.create();
}
四、Fragment之间的数据传递(把数据传到对话框)
1)、传参
public static DatePickerFragment newInstance(Date date){
Bundle bundle=new Bundle();
bundle.putSerializable(DatePickerFragment.DIALOG_DATE,date);
DatePickerFragment fragment=new DatePickerFragment();
fragment.setArguments(bundle);
returnfragment;
}
2)、获取参数( 在对话框那获取传来的数据)
mDate=(Date)this.getArguments().getSerializable(DatePickerFragment.DIALOG_DATE);
3)、把值传回去(对话框把数据传给它的调用者)
//builder.setPositiveButton(android.R.string.ok,null);
builder.setPositiveButton(android.R.string.ok,newDialogInterface.OnClickListener(){
@Override
public voidonClick(DialogInterface dialog,intwhich) {
DatePickerFragment.this.sentResult(Activity.RESULT_OK);
}
});
//返回数据
private void sentResult(int resultCode){
if(this.getTargetFragment()==null){
return;
}
Intent intent=newIntent();
intent.putExtra(DatePickerFragment.DIALOG_DATE,this.mDate);
this.getTargetFragment().onActivityResult(this.getTargetRequestCode(),resultCode,intent);
}
4)、接收方重写方法,拿到数据后想干嘛就干嘛
@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!= Activity.RESULT_OK){
return;
}
if(requestCode==CrimeFragment.REQUEST_CODE){
Date date=(Date) data.getSerializableExtra(DatePickerFragment.DIALOG_DATE);
this.crime.setmDate(date);
this.mDateButton.setText(date.toString());
}
}
子Activity由父Activity的fragment调用startActivityForResult()启动。子Activity被销毁后,父Activity会接收到onActivityResult()的调用请求,并将之转发给启动子Activity的fragment。