开发者

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 tried doing it with an intent but the application force closed with this error msg:

E/AndroidRuntime( 239): android.content.ActivityNotFoundException: Unable to find explicit 开发者_StackOverflow社区activity class {com.xxxx/com.xxxx.xxxxPreference}; have you declared this activity in your AndroidManifest.xml?

How should I do this? It's ok to add that DialogPreference to the manifest?


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 resource
addPreferencesFromResource(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 DialogPreference
    MyDialogPreference dp = (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:

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


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

<activity android:name=".path.to.MyActivity"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜