I created a new class that extends the DialogFragment
class:
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();
}
}
And somewhere in my main activity (inside of a button onClick), I want to show this dialog. So I tried:
SaveDataDialog sdd = new SaveDataDialog();
sdd.getDialog().show();
Second line gives a null pointer exception.
How do I show the dialog? That's all I want to do.
try
sdd.show();
instead of
sdd.getDialog().show();
since your dialog extends DialogFragment, you don't have to call .getDialog()
More details: http://android-developers.blogspot.com/2012/05/using-dialogfragments.html
您的SaveDataDialog
扩展了DialogFragment
,您可以调用sdd.show()
来显示DialogFragment
。
Inside your activity use the following code to show your dialog fragment.
SaveDataDialog saveDataDialog = new SaveDataDialog();
saveDataDialog.show(getFragmentManager(), SaveDataDialog.class.getName());
http://developer.android.com/reference/android/app/DialogFragment.html#show(android.app.FragmentTransaction , java.lang.String)
If your application supports Android versions before 3.0.x. You will need to use the support library and import android.app.v4.DialogFragment.
http://developer.android.com/tools/support-library/index.html
This link is really helpful to me hope it helps you too. Here's a link !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.