Dialog d = new AlertDialog.Builder(getActivity())
.setView(/* View */)
.setTitle(/* String */)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
// do something
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
// do something
})
.create();
创建
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.bignerdranch.android.criminalintent.date";
private static final String ARG_DATE = "date";
// 创建Fragment实例,接受Date参数为初始化要素
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
// 创建对话框
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setView(/* View */)
.setTitle(/* String */)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
// do something
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
// do something
})
.create();
}
}
显示
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(/* 数据 */);
dialog.setTargetFragment(/* 目标Fragment */, /* 标签 */);
dialog.show(manager, DIALOG_DATE);
注意事项
- 使用
AppCompat
兼容库版本的DialogFragment
和AlertDialog
能获得长期的支持。
- 使用
DialogFragment
来管理对话框,可以更灵活地显示对话框。设备配置改变时,直接使用对话框也会使数据丢失。
实用第三方库