Scroll to / set position of custom list preference
Asked Answered
B

1

6

I have a custom preferencefragment that contains two custom listpreferences. Due to the dynamic nature of the two lists, each time my parent fragment is loaded, I refresh these two fragments by creating a new instance of the custom preferencefragment:

if(themeListFragment != null) {
    themeListFragment = new ThemeListFragment();
    //init fragment
    getFragmentManager().beginTransaction()
            .replace(R.id.themeFragmentCont, themeListFragment)
            .commit();
}

This works perfectly and renders the custom list preferences. Each of these two list preferences are defined by a custom listpreference:

//setup themes list
if(lp == null) {
    lp = (ThemeListPreference) findPreference("theme_list");
    lp.setOnPreferenceChangeListener(this);
    refreshThemes();
}

My custom listpreference is mostly there to do some operations before creating the dialog, so it overrides that method:

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    int index = preferences.getInt(getContext().getString(R.string.theme_id),getContext().getResources().getInteger(R.integer.default_theme_id));

    System.out.println(index);

    ListAdapter listAdapter = new ThemeListAdapter(getContext(),
            R.layout.image_list_row, this.getEntries(),
            themes, index,
            this);

    builder.setAdapter(listAdapter, this);

    super.onPrepareDialogBuilder(builder);
}

Everything works great from start to finish, but when the lists get long enough, scrolling becomes an issue since the list popup doesn't auto-scroll to the selected preference item.

All of the posts around the web for this issue assume that you can get the underlying listview by id and just do the smooth scroll (or similar) to jump to the proper list item. However, in my case, there isn't a list view id, so I can't reference it (at least from my limited knowledge). Is there any possible way to do this?

Betjeman answered 19/4, 2016 at 0:56 Comment(0)
E
0

The ListPreference uses AlertDialog.Builder.setSingleChoiceItems(), which ensure the currently selected item is visible. So, in your case replace

builder.setAdapter(listAdapter, this);

with:

builder.setSingleChoiceItems(listAdapter, index, this);
Emunctory answered 26/4, 2016 at 10:36 Comment(2)
Thanks for the suggestion - the list appears to have the exact same functionality though unfortunately. It still renders at the top of the list and requires scrolling down to see the selected item.Betjeman
Strange, the only difference I can see with your case is that I subclassed DialogPreference instead of ListPreference, because I had problems with the way the ListPreference handle the lists of labels and valuesEmunctory

© 2022 - 2024 — McMap. All rights reserved.