How To Set Scroll Position For Long Preferencescreen
Solution 1:
I know this is an old one, so this answer is just for reference.
To auto-select a given screen, all you have to do is setPreferenceScreen()
(this is for a pre-Honeycomb non-Fragment PreferenceActivity).
Once you're on the correct PreferenceScreen, you can indeed use getListView().smoothScrollToPosition(position)
(but this is a Froyo+ method), or you can use getListView.setSelection(position)
.
But how to get the position?
First, watch out for the trap: PreferenceActivity.getListAdapter()
does not return the actual ListAdapter, but a local instance variable which is disconcertingly not in sync with PreferenceActivity.getListView().getAdapter()
(and usually null).
Second, trying to use Preference.getOrder()
returns the order of the Preference object within its parent, which is what you want to use for the position only if you're not using PreferenceCategories
since what you need is its order within the PreferenceScreen.
If you are using PreferenceCategories, you need to iterate over the items in the adapter (for (int i = 0; i < adapter.getCount(); i++)
until you find the right one, and use its position.
Another corner of the Android SDK that is in dire need of some attention…
Solution 2:
Add this function to your PreferenceFragment
publicvoidscrollToItem(String preferenceName) {
ListViewlistView= ButterKnife.findById(getView(),android.R.id.list);
Preferencepreference= findPreference(preferenceName);
if (preference != null && listView != null) {
for (inti=0; i < listView.getAdapter().getCount(); i++) {
PreferenceiPref= (Preference) listView.getAdapter().getItem(i);
if (iPref == preference) {
listView.setSelection(i);
break;
}
}
}
}
Lets say you have settings.xml with this
<Preference
android:icon="@drawable/ic_action_email"
android:key="emailSupport"
android:title="@string/email_support" />
You can call
scrollToItem("emailSupport");
Note: You may need to replace listView.setSelection(i)
with listView.smoothScrollToPosition(i)
Solution 3:
You can just use scrollToPreference
:
Example:
scrollToPreference(preferenceKey)
or:
scrollToPreference(preference)
Solution 4:
Since PreferenceActivity extends ListActivity, you can call getListView()
to get the ListView containing your preferences, and then use listView.smoothScrollToPosition()
to scroll to a specific row in the list. I haven't actually tried this before, but it should work.
Post a Comment for "How To Set Scroll Position For Long Preferencescreen"