androidpreferencedialog-preference

Android YesNoDialogPreference


You may think this is a duplicate question but i looked up almost every existing answer and i still did not get it right. Here is my question:

  1. I want to create a default YesNoDialogPreference by extending the DialogPreferenceclass
  2. Creating a preference using YesNoDialogPreference in prefs.xml
  3. In the MainActivity i want to set an onClickListener for Yes and No options

I have tried doing this using AlertDialog.Builder but it didn't work, i've also tried to use com.android.internal.preference.YesNoPreference and it did work cause of R.attr error Can somebody please give me a full answer...PLEASE!!, i have been struggling with this for weeks now.

Here's my code: YesNoDialogPreference.java

import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;

public class YesNoDialogPreference extends DialogPreference {

    public YesNoDialogPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        persistBoolean(positiveResult);
    }

}

The preference from prefs.xml

<com.me.myapp.YesNoDialogPreference
            android:key="KEY"
            android:dialogMessage="You sure ?"
            android:title="Do something"
            android:summary="will do something"
            />

I do not know how to link them in the MainActivity.


Solution

  • What you are trying to achieve does not make sense. The MainActivity is not active so can't be the target of the dialog. You need an onClick handler in your YesNoDialogPreference which then does what you want. You typically safe the value in your settings and read that value in all other places - like your MainActivity. Here is a code sample: How to get the DialogPreference POSITIVE_BUTTON to work on OnClick?