一健民、創(chuàng)建對話框
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之間的數(shù)據(jù)傳遞(把數(shù)據(jù)傳到對話框)
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)欲低、獲取參數(shù)( 在對話框那獲取傳來的數(shù)據(jù))
mDate=(Date)this.getArguments().getSerializable(DatePickerFragment.DIALOG_DATE);
3)辕宏、把值傳回去(對話框把數(shù)據(jù)傳給它的調(diào)用者)
//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);
}
});
//返回數(shù)據(jù)
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)、接收方重寫方法,拿到數(shù)據(jù)后想干嘛就干嘛
@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調(diào)用startActivityForResult()啟動砾莱。子Activity被銷毀后瑞筐,父Activity會接收到onActivityResult()的調(diào)用請求,并將之轉(zhuǎn)發(fā)給啟動子Activity的fragment腊瑟。