Going from a PreferenceScreen to a DialogPreference

后端 未结 2 1190
说谎
说谎 2021-01-06 08:12

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

2条回答
  •  花落未央
    2021-01-06 08:51

    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:

    
        
    
    

提交回复
热议问题