I have a ListView inside a Fragment, which is added as a tab inside a ViewPager. I want the users to be able to scroll "backToTop" by simply tapping on the Tab they are already on (onTabReselected()). I already have a working code to do this; However, the code I use takes too long to scroll back to position 0, which is pretty neat on small lists, but on a 250 song collection it can certainly annoy a user.
Here's my code:
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
if (tab.getPosition() == mCurPagerItem) {
final ListView list = (ListView) findViewById(android.R.id.list);
list.smoothScrollToPosition(0);
}
break;
case 1:
if (tab.getPosition() == mCurPagerItem) {
final GridView list = (GridView) findViewById(R.id.artist_grid);
list.smoothScrollToPosition(0);
}
break;
case 2:
if (tab.getPosition() == mCurPagerItem) {
final ExpandableListView list = (ExpandableListView) findViewById(R.id.exp_list);
list.smoothScrollToPosition(0);
}
break;
default:
break;
}
}
Where I switch between positons as my different fragments have different "list" types. As I said, this code works certainly well, but is there a faster way to scroll back to top? Something that is more instant that is.
And just to clarify, when I say it "takes too long", that is because smoothScrollToPosition is in itself a slow way to scroll on the list, supposedly to make it nicer looking.
Note I did try:
list.scrollTo(0, 0);
but that actually doesn't seem to do anything to the listView's current position. I imagine that is more a View call, that a ListView method itself.
Any ideas?
Try calling setSelection()
, it doesn't perform any animations:
list.setSelection(0);
int position = 10; // 10 or other
if (list.getFirstVisiblePosition() > position) {
list.setSelection(position);
list.smoothScrollToPosition(0);
} else {
list.smoothScrollToPosition(0);
}
Updated:2013-10-27 From API level 11, you can use smoothScrollToPositionFromTop (int position, int offset, int duration)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With