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 然后以一种我什至无法描述的方式表现得很疯狂......

任何想法?

4

2 回答 2

5

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

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

它在 ScrollView 中对我有用(检查这个答案)。

于 2010-11-24T17:00:13.277 回答
2

我制作了对其他人有用的列表视图滚动功能,它们适用于每个 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;
}
于 2012-11-16T03:03:16.817 回答