Android ListView将项目添加到顶部而没有列表视图滚动

Har*_*ten 23 android listview scroll

我有一个listView,我想在列表视图的顶部添加新项目,但我不希望列表视图滚动其内容.我希望用户在添加新项目之前查看他正在查看的相同项目.

这是我向ListView添加新项目的方法:

this.commentsListViewAdapter.addRangeToTop(comments);
this.commentsListViewAdapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

这是addRangeToTop方法:

public void addRangeToTop(ArrayList<Comment> comments)
{
    for (Comment comment : comments)
    {
        this.insert(comment, 0);        
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的listView:

<ListView
    android:id="@+id/CommentsListView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/AddCommentLayout" 
    android:stackFromBottom="true" >        
</ListView>
Run Code Online (Sandbox Code Playgroud)

我想要做的是在用户滚动到顶部时加载旧注释.

谢谢您的帮助.

Har*_*ten 29

我在这里找到了解决方案在调用notifyDataSetChanged之后在ListView中保留位置

抱歉重复的问题.最终的代码是这样的:

    int index = this.commentsListView.getFirstVisiblePosition() + comments.size();
    View v = this.commentsListView.getChildAt(commentsListView.getHeaderViewsCount());
    int top = (v == null) ? 0 : v.getTop();         

    this.commentsListViewAdapter.AddRangeToTop(comments);
    this.commentsListViewAdapter.notifyDataSetChanged();    

    this.commentsListView.setSelectionFromTop(index, top);
Run Code Online (Sandbox Code Playgroud)


Kam*_*med 9

可能这就是你要找的东西:

android:transcriptMode="normal"
Run Code Online (Sandbox Code Playgroud)

"这会使列表在收到数据集更改通知时自动滚动到底部,并且只有在屏幕上已显示最后一项时才会自动滚动到底部." - 正如这里引用的那样