Skip to content Skip to sidebar Skip to footer

Going From A Preferencescreen To A Dialogpreference

My application has a setting menu which is actually a PreferenceActivity. When it's created, if a boolean value is not set I want to go to the DialogPreference which sets that. I

Solution 1:

A DialogPreference isn't an Activity in its own right. It's just a Preference which displays a Dialog when clicked.

The problem is that there's no obvious way programmatically click a Preference. However, since you're using DialogPreference you've already got you own subclass of it. So we can solve our problem by adding the following method to your subclass of DialogPreference:

//Expose the protected onClick method
void show() {
    onClick();
}

Then in the onCreate() of your PreferencesActivity you'll have something like this to load the preferences from your XML file:

// Load the preferences from an XML resourceaddPreferencesFromResource(R.xml.preferences);

After that you can put some code like this:

booleanProp = true; //set this to the value of the property you're checking     if (! booleanProp) {
    //Find the Preference via its android:key//MyDialogPreference is your subclasss of DialogPreferenceMyDialogPreferencedp= (MyDialogPreference)getPreferenceScreen().findPreference("dialog_preference");  
    dp.show();
}

This is a bit of hack, as exposing protected methods isn't ideal, but it does work.

Another option would be to replace the Dialog with a PrefenceActivity which contained all the options you wish to maintain and then you could launch it via an Intent, but I'm assuming there's a good reason that you want your own custom Dialog with a specific layout. If you do want a second PreferenceActivity you can add it to your preferences XML file as follows:

<PreferenceScreenandroid:title="@string/title_of_preference"android:summary="@string/summary_of_preference"><intentandroid:action="your.action.goes.HERE"/></PreferenceScreen>

Solution 2:

To start an activity with an Intent, the activity must be in the Android manifest. Just add a line like:

<activityandroid:name=".path.to.MyActivity"/>

Post a Comment for "Going From A Preferencescreen To A Dialogpreference"