安卓ListView滚动到指定位置

3
我有一个LinearLayout,其中包含其他视图和一个ListView。通过点击按钮,从另一个视图加载此视图。
这个按钮指定了ListView中需要作为第一个可见元素的元素。填充列表的元素是通过HTTP从外部服务器检索的。
问题在于我无法将第N个元素放在列表中的第一个位置。请注意,我不想将它从当前位置移动到新位置,我希望列表滚动。
我尝试使用setSelected()、scrollTo(x,y)和scrollBy(x,y),但没有成功。
我还尝试过这段代码,虽然很丑陋,但我只是想试试看它是否有效:
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的表现非常“疯狂”,我甚至无法描述它的行为.....

有什么想法吗?

2个回答

5

尝试将其添加到消息队列中

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

在ScrollView中,它对我起作用(查看这个答案)。


我也尝试了setSelected并且它也有效。所以,我已经找到了解决问题的方法!我没有清楚地理解为什么这样会起作用 :/ - 0m4r

3

我创建了一些函数,它们可以对ListView的滚动非常有用,在每个Android版本、模拟器和设备上都能正常工作。其中itemheight是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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接