Search code examples
androidandroid-listviewandroid-scroll

Android ListView scrollTo


I have a LinearLayout that contains some other views and among those a ListView. This view is loaded from another one by clicking a button.

This button somehow specify what element in the ListView needs to be the first visible one in the list. The elements that populates the list are retrieved via HTTP from an external server.

The problem is that I can get the Nth element to be the first in the list. Please note, I do not want to move it form it current position to a new one, I want the list to scroll.

I have tried with setSelected() and scrollTo(x,y) and scrollBy(x,y) but with no luck.

I have also gave a try to this pice of code, as ugly as it is, but I just wanted to try f it was working:

ListView categoryList = (ListView)findViewById(R.id.category_list);
        categoryList.post(new Runnable() {
            @Override
            public void run() {
                Log.d(this.getClass().getName(), "CategoryActivity.scrollToIndex: " + CategoryActivity.scrollToIndex);
                if(CategoryActivity.scrollToIndex>0){
                    ListView categoryList = (ListView)findViewById(R.id.category_list);
                    categoryList.setScrollContainer(true);
                    categoryList.scrollTo(4, CategoryActivity.scrollToIndex * 50);
                    categoryList.requestLayout();

                }
            }
        });

And this gave me some success, but the ListView was then behaving crazy in a way I am not even able to describe....

Any idea?


Solution

  • Try to add it to the message queue

    categoryList.post(new Runnable() {
        public void run() {
            categoryList.scrollTo(4, CategoryActivity.scrollToIndex * 50);
        }
    });
    

    It worked for me in a ScrollView (check this answer).