带负片的DialogFragment

时间:2014-09-19 09:09:19

标签: android android-dialogfragment

我想在我的应用程序中创建一个About对话框,我希望它有默认对话框的按钮,我决定使用DialogFragment,所以我就这样做了

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;
}

}

然后从活动中调用它

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

然后我收到此错误

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

@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