【问题标题】:Android ListView add items to top without list view scroll [duplicate]Android ListView在没有列表视图滚动的情况下将项目添加到顶部[重复]
【发布时间】:2013-03-24 10:41:10
【问题描述】:

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

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

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

这是addRangeToTop 方法:

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

这是我的列表视图:

<ListView
    android:id="@+id/CommentsListView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/AddCommentLayout" 
    android:stackFromBottom="true" >        
</ListView>

我想要做的是在用户滚动到顶部时加载旧的 cmets。

感谢您的帮助。

【问题讨论】:

    标签: android listview scroll


    【解决方案1】:

    我在这里找到了解决方案Retaining position in ListView after calling notifyDataSetChanged

    抱歉,有重复的问题。 最后的代码是这样的:

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

    【讨论】:

    • 很好的解决方案,谢谢!
    【解决方案2】:

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

    android:transcriptMode="normal"
    

    “当收到数据集更改通知并且仅当最后一项已在屏幕上可见时,这会使列表自动滚动到底部。” - 引用here

    【讨论】:

    【解决方案3】:

    还可以看看 ListView 的方法public void setSelection (int position)。添加新的 cmets 并通知您的适配器后,您可以使用它来保持当前项目处于选中状态。

    // Get the current selected index
    int previousSelectedIndex = yourListView.getSelectedItemPosition();
    
    // Change your adapter
    this.commentsListViewAdapter.AddRangeToTop(comments);
    this.commentsListViewAdapter.notifyDataSetChanged();
    
    
    // Determine how many elements you just inserted
    int numberOfInsertedItems = comments.size();
    
    // Update the selected position
    yourListView.setSelection(previousSelectedIndex + numberOfInsertedItems);
    

    注意:代码未经测试。祝你好运

    【讨论】:

    • 谢谢你,这在某种程度上可行,但不是很好。它向上滚动两个项目。我认为这是因为 List 视图不是按项目滚动而是按像素滚动,而 setSelection 完全滚动到项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多