Search code examples
androidandroid-preferences

How to open or simulate a click on an android Preference, created with XML, programmatically?


I've an android application with preferences declared in XML, loaded with addPreferencesFromResource. The user can open preferences, click on each item and edit them, all works.

One preference I have is:

        <ListPreference android:key="abc"
            android:title="@string/abc"
            android:summary="@string/cde"
            android:persistent="true"/>

How can I show the preference dialog to a user automatically (without the need for the user to go to the preference screen and click on it?).

I tried ( (android.preference.DialogPreference) prefMgr.findPreference( "abc" )).showDialog(null), but is says it is a protected method...? Called it from my main activity (which is a PreferenceActivity), that's why it obviously cannot work. But how else?

EDIT

I just found two threads (1, and 2) with the idea to use findViewById to access the preference, but with no success. It always returns null (does for me, too).

It looks like there is really no possibility to do this from code.


Solution

  • You could have extended ListPreference to create your dialog, then included your own public method that calls the protected showDialog method of ListPreference. Something like:

    public void show()
    {
        showDialog(null);
    }
    

    This way you won't run into the issue of getOrder() not working when there are PreferenceGroups as several people have pointed out in the comments your answer.

    This can be done with any preference types that has a protected showDialog method.