Android switching between PreferenceScreens

2019-06-06 12:26发布

问题:

I have a PreferencesScreen, that has some Preferences and a sub-screen. It looks like this:

<PreferenceScreen android:key="root">

    <Preference android:key="first" />

    <PreferenceScreen android:key="subScreen" />
        <Preference android:key="second" />
        <Preference android:key="third" />
    </PreferenceScreen>

</PreferenceScreen>

When user clicks the subscreen, he is moved to the subscreen view. Now I want to redirect the user to "root" preference screen when he clicks on "second" or "third". I don't seem to find the right API to either close the subscreen, or focus the previous one. Ideas?

回答1:

Preference subscreen is displayed as a dialog, in your case it would be enough to dismiss the dialog representing appropriate PreferenceScreen. Insert the following snippet into onPreferenceClick() method of OnPreferenceClickListener you probably set for "second" and "third" preferences to close the dialog:

PreferenceScreen ps = (PreferenceScreen)PrefsActivity.this.getPreferenceScreen()
    .findPreference("subScreen");
ps.getDialog().dismiss();

where PrefsActivity is the enclosing instance of PreferenceActivity that is used in your application.



回答2:

I have no idea why you have bare Preference elements in the first place. Off the top of my head, I cannot think of anywhere in Settings where the user would encounter your desired behavior, so what you are trying to do is likely to be unexpected. Also, I recommend you start to move away from nested PreferenceScreen elements, as the new direction is PreferenceFragments for Honeycomb onward.

That being said, try setPreferenceScreen() on PreferenceActivity and see if it gives you what you need.