Search code examples
androidandroid-dialogfragment

DialogFragment with negative button


I want to make an About dialog in my app, and I want it to have the default dialog's button, and I decided to use DialogFragment, so I made it like this

public class AboutDialog extends DialogFragment {

public AboutDialog() {
    // Empty constructor for fragment
}

@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("About");
    builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dismiss();
        }
    });
    return builder.create();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.about_dialog, container);
    getDialog().setTitle(getString(R.string.action_about));
    return rootView;
}

}

then call it from the Activity like this

AboutDialog about = new AboutDialog();
        about.show(getSupportFragmentManager(), null);

and then I get this error

android.util.AndroidRuntimeException: requestFeature() must be called before adding content

How do I fix this?


Solution

  • @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.about_dialog, null));
        builder.setMessage("Test")
               .setPositiveButton("fire", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // FIRE ZE MISSILES!
                   }
               })
               .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();
    }
    
    remove your onCreateView