workarounds for GridView.scrollTo()?

2019-02-10 09:57发布

问题:

As mentioned here, Android's GridView.scrollTo() doesn't work. The method the solution mentioned, setSelectedPosition, doesn't seem to exist in GridView

smoothScrollToPosition does work, but I really don't want the animation.

For context, I have a CursorAdapter-backed GridView, and I want the view to "reset", i.e. scroll to the top, when I change the cursor.

回答1:

I've been using setSelection(int position) for this, and it seems to be working just fine. To scroll to the top, just use 0 for position.

From the docs:

If in touch mode, the item will not be selected but it will still be positioned appropriately.

Edit: Added code to post setSelection as a Runnable:

albumsView.post(new Runnable() {
    @Override
    public void run() {
        albumsView.setSelection(0);
    }
});


回答2:

I have found that in order to reliably use gridView.setSelection(index), I have to first call gridView.setAdapter() (even if the adapter has already been set and has not changed). Like so:

gridView.setAdapter(gridAdapter);
gridView.setSelection(index);