Search code examples
javaandroiddialoglistenerpreference

DialogPreference set title of Dialog


I have a DialogPreference. I would like to set its Dialog title (setTitle()), but it is not working.

My code:

public class RestoreDefaultApperanceDialogPreference extends DialogPreference {

    Dialog dialog;

    public RestoreDefaultApperanceDialogPreference(Context context,
            AttributeSet attrs) {
        super(context, attrs);

        dialog = getDialog();
        //dialog.setTitle("Restore default colors?"); //<- NOT WORKING!
        // TODO Auto-generated constructor stub
    }

    public RestoreDefaultApperanceDialogPreference(Context context,
            AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }
}

XML FILE (Preference category):

<PreferenceCategory android:title="Appearance settings">
        <com.example.dictionary.ColorSelectPreference
            android:key="onlineRecognitionColor"
            android:title="Online recognision results color" 
            android:summary="Customize color of online recognition results."
        />
        <com.example.dictionary.ColorSelectPreference
            android:key="offlineRecognitionColor"
            android:title="Offline recognition results color" 
            android:summary="Customize color of offline recognition results."
        />
        <com.example.dictionary.RestoreDefaultApperanceDialogPreference
            android:key="restoreDefaultApperance"
            android:title="Restore default apperance" 
            android:summary="Choose this option to restore default apperance settings." 
        />
 </PreferenceCategory>

How can I setTitle to this Dialog


Solution

  • Use setDialogTitle() and override onDialogClosed() to capture the button clicks and perform your actions.

    public RestoreDefaultApperanceDialogPreference(Context context,
            AttributeSet attrs) {
        super(context, attrs);
    
        setDialogTitle("Restore default colors?"); // <- this should work
    }
    
    
    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
    
        if (positiveResult) {
            // OK button is pressed
        } else {
            // Cancel button is pressed
        }
    }