문제

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?

도움이 되었습니까?

해결책

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).

다른 팁

i made functions that could be useful for others for listview scrolling, they work for me in every android version, emulator and device, here itemheight is the fixed height of view in the listview.

int itemheight=60;
public void scrollToY(int position)
{
    int item=(int)Math.floor(position/itemheight);
    int scroll=(int) ((item*itemheight)-position);
    this.setSelectionFromTop(item, scroll);// Important
}
public void scrollByY(int position)
{
    position+=getListScrollY();
    int item=(int)Math.floor(position/itemheight);
    int scroll=(int) ((item*itemheight)-position);
    this.setSelectionFromTop(item, scroll);// Important
}
public int getListScrollY()
{
    try{
    //int tempscroll=this.getFirstVisiblePosition()*itemheight;// Important
    View v=this.getChildAt(0);
    int tempscroll=(this.getFirstVisiblePosition()*itemheight)-v.getTop();// Important
    return tempscroll;
    }catch(Exception e){}
    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top