Android: how to open a ListPreference dialog from outside PreferenceActivity/PreferenceFragment?
Asked Answered
B

1

6

I've created a settings menu for my app based on PreferenceFragment, and would like to access the settings dialog(s) from elsewhere in the app without having to open the settings menu.

My settings menu has this:

settings menu

and I want to show the same dialog when I click this menu item from the main activity:

main activity

The main Activity has one ListFragment which is where all of the UI handling code is. Neither is a PreferenceActivity or PreferenceFragment.

I just want to invoke the same PreferenceFragment object to get to the dialog, otherwise I'd have to write custom code to handle the preference changes manually, which I'd like to avoid.

I thought adding the PreferenceFragment to the FragmentManager in the main Activity would properly instantiate it, but it doesn't seem to work.

From my menu handler code for the "Sort" option:

    SettingsFragment fragment = (SettingsFragment) getFragmentManager().findFragmentByTag(SettingsActivity.FRAGMENT_TAG);

    // first run case
    if (fragment == null) {
        fragment = SettingsFragment.newInstance(getActivity());
        getFragmentManager().beginTransaction().add(fragment, SettingsActivity.FRAGMENT_TAG).commit();
    } 

    CustomListPreference listPref = (CustomListPreference) fragment.findPreference(SettingsFragment.KEY_PREF_SORTORDER);
    listPref.show(); // invokes showDialog(null)

This crashes with a NullPointerException on listPref, which shows the PreferenceFragment was not properly initialized.

Is there any way to achieve this effect, or do I have to write the functionality as an AlertDialog and manually handle the Preference changes?

Brame answered 25/6, 2014 at 8:32 Comment(0)
P
1

I think you'll have to write this functionality yourself outside of the Preference classes.

Preference, PreferenceActivity, and PreferenceFragment were all designed to work together to provide a consistent UIX for android apps. As such it's recommended to use them together as they were intended.

You can't directly replicate the UI of PreferenceActivity or PreferenceFragment outside of those two classes in a regular activity because the UI is built from Preference objects, not View objects like regular Activities. So if you want that particular UI you'd have to try and duplicate it using custom Views.

https://discussions.udacity.com/t/way-to-do-listpreference-outside-of-settings-menu/45473

Perreira answered 28/1, 2016 at 4:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.