我创建了一个扩展类的新DialogFragment
类:
public class SaveDataDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.save_data_dialog, null))
// Add action buttons
.setPositiveButton(R.string.save_data, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(), "Testing positive button", Toast.LENGTH_LONG).show();
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SaveDataDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
在我的主要活动中的某个地方(在按钮 onClick 内),我想显示这个对话框。所以我尝试了:
SaveDataDialog sdd = new SaveDataDialog();
sdd.getDialog().show();
第二行给出了一个空指针异常。
如何显示对话框?这就是我想做的。