-1

I have a cutstom DialogFragment to show a message to the user:

public class MensajeDialogFragment extends DialogFragment {
    TextView mTvMensaje;
    TextView mTvTitulo;
    Button mBtnAceptar;
    Button mBtnCancelar;            

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        View dialogView = inflater.inflate(R.layout.layout_mensaje_dialog, null);
        mTvTitulo = (TextView) dialogView.findViewById(R.id.tvTitulo);
        mTvMensaje = (TextView) dialogView.findViewById(R.id.tvMensaje);
        mBtnAceptar = (Button) dialogView.findViewById(R.id.btnAceptar);
        mBtnCancelar = (Button) dialogView.findViewById(R.id.btnCancelar);

        mTvTitulo.setText(getArguments().getString(getString(R.string.bundle_titulo), ""));
        mTvMensaje.setText(getArguments().getString(getString(R.string.bundle_mensaje), ""));
        mBtnAceptar.setText(getArguments().getString(getString(R.string.bundle_aceptar), ""));
        mBtnCancelar.setText(getArguments().getString(getString(R.string.bundle_cancelar), ""));    

        builder.setView(dialogView);

        getDialog().setCanceledOnTouchOutside(true);

        return builder.create();
    }


}

But when I reach the getDialog().setCanceledOnTouchOutside(true), I am getting NullPointerException beacuse the getDialog() is returning null.

What am I doing wrong? I want to close the dialog when the user clicks outside of it.

IIRed-DeathII
  • 1,117
  • 2
  • 15
  • 34

1 Answers1

1

Since you are using DialogFragment, dialog won't be initialized on onCreate of DialogFragment. I believe DialogFragment by default closes when user clicks outside it.You don't have to declare it explicitly. If you still want to call this function, then DialogFragment has a function called

 DialogFragment.setCancelable(boolean)

EDIT

If the above code doesn't work, you can try calling

 getDialog().setCanceledOnTouchOutside(true);

inside onCreateView as Dialog object will on be initialized on getLayoutInflater during onCreateDialog. So by the time it reaches onCreateView dialog object will be initialized.

Fabin Paul
  • 1,701
  • 1
  • 16
  • 18