0

I am implementing a DialogPreference in a class. I want that when the positive button of the dialog is clicked, the dialog should not dismiss. I am using the logic from this answer.

Insided the class I use:

protected void onPrepareDialogBuilder(Builder builder) {
    super.onPrepareDialogBuilder(builder);

    final AlertDialog d = builder.create();

    d.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {

            Toast.makeText(mContext, "inside", Toast.LENGTH_SHORT).show();
            Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    // TODO Do something

                    // Dismiss once everything is OK.
                    d.dismiss();
                }
            });
        }
    });
}

But when I open the dialog, I do not see the Toast,and the dialog closes. So how is my implementation of that answer wrong?

Community
  • 1
  • 1
Born Again
  • 2,139
  • 4
  • 25
  • 27

2 Answers2

0

Your situation is a bit different. You can't call "builder.create()" in onPrepareDialogBuilder method. See API reference here.

Unfortunately this means that you don't have access to dialog object and you can't set onShowListener. Try extending Preference class and build your dialog there.

Chiral Code
  • 1,426
  • 2
  • 12
  • 12
-1

There is a hack you can apply (ugly but will work). Try the following override:

@Override
protected View onCreateDialogView() {
    View view = super.onCreateDialogView();

    view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View view) {
            Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    // TODO Do something

                    // Dismiss once everything is OK.
                    d.dismiss();
                }
            });            }

        @Override
        public void onViewDetachedFromWindow(View view) {

        }
    });

    return view;
}
Aleksander Lech
  • 1,105
  • 12
  • 16