Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a "faster" backToTop - ListView

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?

like image 539
daniel_c05 Avatar asked Jan 14 '23 16:01

daniel_c05


2 Answers

Try calling setSelection(), it doesn't perform any animations:

list.setSelection(0);
like image 66
Sam Avatar answered Jan 21 '23 20:01

Sam


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)

like image 31
c0ming Avatar answered Jan 21 '23 19:01

c0ming