【问题标题】:Android ListView : How to keep the ListView at the top when its content changes?Android ListView:当 ListView 的内容发生变化时,如何将其保持在顶部?
【发布时间】:2012-09-19 09:23:18
【问题描述】:

我有一个视图,其中包含一个绑定到光标适配器的 ListView。当光标内容更改时,我想将 ListView 保持在顶部,然后在我的自定义光标适配器中添加:

@Override
protected void onContentChanged() {
    // ...
    myListView.scrollTo(0, 0);
}

但这不起作用。然后我在某处读到这样的动作:

myListView.post(new Runnable() {
    public void run() {
        myListView.scrollTo(0, 0);
    }
});

但这也不起作用。

当 ListView 的内容发生变化时,如何让其保持在顶部?

编辑:

只是为了尝试,我添加了一个按钮并在其 onClickListener 中调用了 scrollTo() ,但它不起作用!我错过了什么?

【问题讨论】:

    标签: android android-listview simplecursoradapter android-cursor


    【解决方案1】:

    尝试 setSelection(0) 而不是 scrollTo 以到达列表视图的顶部位置。

    【讨论】:

    • @jafar 这应该可以。 ListView 的 scrollTo 适用于它自己的 ListView 但 listview 不可滚动,因此结果什么都没有。 setSelection 可以解决问题,因为它适用于列表视图的适配器
    • 还要注意setSelection需要在adapter.notifyDataSetChanged()之后调用。
    • 嗨@weakwire,你说srollTo 不适用于ListView?为什么会这样?
    • 嗨@KarenAnne。有用。但不适用于列表视图的滚动。它适用于滚动视图本身(包含列表)。所以无法使用。
    • 您还应该解释为什么ScrollTo 不起作用?
    【解决方案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;
    }
    

    【讨论】:

    • 以上函数应该添加到继承/扩展ListView的类中
    • 硬编码高度不是一个好主意,列表可以处理混合元素以及可变高度的多行文本。我也写了很多花哨的ListViews,既不需要扩展实际的课程。考虑在从适配器获取特定项目后调用 View.measure(int,int) 获取特定项目的高度。
    • 你说得对,硬编码高度不是正确的方法,但常用的列表视图具有固定高度元素,滚动功能对它们不起作用,这只是滚动功能的一种解决方法。您可以根据自己的需要修改它们,“View.measure(int,int)”也可以使用,这取决于您如何修改它们以满足您的需求。
    • @Diljeet 我改进了您的 scrollToY 代码,它不假定每个项目的高度相同。而不是从高度计算项目位置。只需将位置插入 setPositionFromTop gist.github.com/Kisty/e2c3cd956a01a19661e8
    【解决方案3】:

    ListView 的scrollTo 适用于ListView 它自己作为View

    setSelection(0) 可以解决问题,因为它适用于列表视图的适配器

    【讨论】:

    • 还要注意setSelection需要在adapter.notifyDataSetChanged()之后调用。
    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多