Search code examples
androidandroid-preferences

Preference with Confirm Dialog


I am having a hard time making a Preference with Dialog, none of the methods suggested in the site works for me. So here is what I have first. In MainActivity I have this

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_stage_1, menu);
    return true;
}

This opens the menu, and when you choose Settings, in the next screen there is only one preference, created from this preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<Preference
    android:summary="clears all data"
    android:title="Reset Data" >
    <intent
        android:targetClass="com.example.myapp.settings.DialogActivity"
        android:targetPackage="com.example.myapp" >
    </intent>
</Preference>

I want when I click this option, a dialog to appear with Yes and No button, so I ca define somewhere what the buttons will do programatically. How can I do it?


Solution

  • You can extend the DialogPreference. Override the onDialogClosed method, which is called when the Dialog closes. The argument to the method indicates whether user selected positive or negative button.

    CustomDialogPreference.java :

        public class CustomDialogPreference extends DialogPreference {
            public CustomDialogPreference(Context context, AttributeSet attrs) {
                super(context, attrs);
    
                // Set the layout here                
                setDialogLayoutResource(R.layout.custom_dialog);
    
                setPositiveButtonText(android.R.string.ok);
                setNegativeButtonText(android.R.string.cancel);
    
                setDialogIcon(null);
            }
    
            @Override
            protected void onDialogClosed(boolean positiveResult) {
                // When the user selects "OK", persist the new value
                if (positiveResult) {
                    // User selected OK
                } else {
                    // User selected Cancel
                }
            }
    
        }
    

    preferences.xml

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <com.example.test1.CustomDialogPreference
            android:key="pref_dialog"
            android:title="dialog"/>
    </PreferenceScreen>
    

    You can refer the official Settings documentation.