user316117
user316117

Reputation: 8271

Programmatically set position in ListView without scrolling

This is for a tablet running Android 4.4.2. I have a ListView with hundreds of items in it and about 20 are visible at a time. The user doesn't want the animation of smooth scrolling. How do I programmatically set the displayed position in a Listview without using smoothScrollToPosition()?

I searched Stack Overflow and in Android ListView setSelection() does not seem to work they suggested this:

mListView.clearFocus();
mListView.post(new Runnable() {
    @Override
    public void run() {
        mListView.setSelection(index);
    }
});

. . . but it just sets the selection; it does not bring that portion of the ListView into view. setSelection() seems like a popular solution all over the web but I couldn't find anything in the documentation saying that setSelection() also sets the position, and it ONLY sets the selection and does not change the position on mine.

In Go to a item in Listview without using smoothScrollToPosition they suggested a solution by Romain Guy ...

[myListView.post(new Runnable() 
{
    @Override
    public void run() 
    {
        myListView.setSelection(pos);
        View v = myListView.getChildAt(pos);
        if (v != null) 
        {
            v.requestFocus();
        }
    }
});] 

The problem with this one is that my ListView is part of a ListActivity being managed via a custom adapter's getView(), so Views that are not visible are recycled, i.e., if I request a child view of a view that's not on the screen it returns null. Anyway, it's really the ListView I'm trying to control, so doing it indirectly via a child View seems awfully indirect.

How do I tell the ListView what part of it I want visible on the screen?

Upvotes: 1

Views: 4014

Answers (2)

Nguyễn Anh Dũng
Nguyễn Anh Dũng

Reputation: 11

Solution is to getView of the row which is currently choosen to getTop.

Then to setSelectionFromTop from current position and getTop to highlight without scrolling:

lv.setSelectionFromTop(position,lv.getAdapter().getView(position,view,parent).getTop());

Upvotes: 1

osayilgan
osayilgan

Reputation: 5893

There is a method in AbsListView, called smoothScrollToPositionFromTop() and it takes duration parameter. So if you set it to 0, you may do it without scrolling, animation.

smoothScrollToPositionFromTop.

Upvotes: 9

Related Questions