Android ListView and setSelection

Android’s ListView is a powerful class that is capable of presenting a list of whatever you wish fairly easily. One of the issues that has vexed me has been scrolling the ListView to a particular entry. While newer Android versions have provided better support in this area, trying to maintain backward compatibility with Android 1.5 presents some challenges. In light of this Google issue and it’s comments, I have come up with a decent method of scrolling a ListView to a particular position if it is not already visible. I clear the focus after setting the selection because users became confused at why an “orange box suddenly appeared” when they did not expressly tap a selection with their finger or scroll with the trackball.

//this method would be part of a ListView class
    @Override
    public void scrollToPosition(final int anItemPos) {
        if (anItemPos!=AdapterView.INVALID_POSITION) {
            int theFirstItemPos = getFirstVisibleItemPos();
            int theLastItemPos = getLastVisibleItemPos();
            if (anItemPos<theFirstItemPos || theLastItemPos<anItemPos) {
                getListView().post(new Runnable() {
                    @Override
                    public void run() {
                        getListView().setSelection(anItemPos);
                        getListView().clearFocus();
                    }    
                });
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *