Search code examples
androidscrollpreferenceactivity

programmatically scroll PreferenceActivity


I have PreferenceActivity with plenty of PreferenceCategories defined in it. If I have the android:key of a given category.

Is it possible programmatically to scroll the Activity to this category?


Solution

  • You can iterate through the preferences in the activity like this:

    PreferenceScreen screen = getPreferenceScreen();
    int i;
    for(i = 0; i < screen.getPreferenceCount(); i++) {
       String key = screen.getPreference(i).getKey();
    
       // be careful, because key will be null if no android:key is specified
       // (as is often the case for PreferenceCategory elements)
       if("myKey".equals(key))
          break;
    }
    
    // PreferenceActivity extends ListActivity, so the ListView is accessible...
    getListView().setSelection(i);
    

    Tested out with Android SDK 14 and it works fine.

    Caution though, calling getListView().setSelection(i) inside onCreate or onResume has no effect. It has to be called after the activity is drawn.

    The getPreferenceCount() method counts all PreferenceCategories and their nested preferences. Not sure what it does for PreferenceScreens, although I'm sure a little experimentation there would be revealing.