Android ListView scrollTo

I have LinearLayoutone that contains some other species and among them ListView. This view is loaded from another by clicking a button.

This button somehow indicates which item in the ListView should be the first visible in the list. Elements that populate the list are retrieved via HTTP from an external server.

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

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

I also tried this piece of code, as if ugly, but I just wanted to try to make it work:

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();

                }
            }
        });

, ListView , ....

?

+3
2

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

ScrollView ( ).

+4

i , , , Android, itemheight - .

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;
}
+2

Source: https://habr.com/ru/post/1776728/


All Articles