简体   繁体   English

将新项目添加到RecyclerView的顶部

[英]Adding new item to the top of the RecyclerView

I am adding an item to recyclerview position 0 programamticly 我正在以编程方式向recyclerview位置0添加一个项目

public void addQuestion(Question question){
    this.questionList.add(0, question);
    notifyItemInserted(0);
}

This is working very well and the items do appear in the list at top BUT the user has to scroll up to see the new item. 这项工作非常好,项目确实出现在顶部的列表中,但用户必须向上滚动才能看到新项目。

Is there any trick how the item appear at top and recyclerview is scrolling up automaticly ? 是否有任何技巧如何项目出现在顶部,Recyclerview自动滚动?

well you can use mRecyclerView.smoothScrollToPosition(int position) 那么你可以使用mRecyclerView.smoothScrollToPosition(int position)

Example: 例:

public void addQuestion(Question question){
    this.questionList.add(0, question);
    notifyItemInserted(0);
    mRecyclerView.smoothScrollToPosition(0);
}

UPDATE: 更新:

if you want to make the scrolling to certain item really smooth you can have a look at answer to this question 如果你想让滚动到某个项目非常顺利,你可以看看这个问题的答案

RecyclerView - How to smooth scroll to top of item on a certain position? RecyclerView - 如何在某个位置平滑滚动到项目顶部?

是的,你可以这样做

mRecyclerView.smoothScrollToPosition(0);

试试这个

mRecyclerView.smoothScrollToPosition(0);

If i understand right and you problem is that you already scrolled to top of list, but when inserting you had to scroll again to see item, you can try my approach to avoid it. 如果我理解正确,你问题是你已经滚动到列表顶部,但插入时你必须再次滚动查看项目,你可以尝试我的方法来避免它。

From my experience, approach with scrolling after insertion works, but animations doesn't look natural. 根据我的经验,插入后滚动的方法可行,但动画看起来并不自然。

If you really want to save animations you can try an approach which helped me in my project: use multi-typed recycler. 如果您真的想保存动画,可以尝试一种方法,帮助我完成项目:使用多类型回收器。 Display additional item of second type at 0 position in your adapter. 在适配器的0位置显示第二种类型的附加项目。 This item can be just a view with little padding, header (if you need) or even an empty view. 这个项目可以只是一个带有小填充,标题(如果需要)甚至是空视图的视图。 Then, notifyItemInserted(1) and you will get nice insert animation. 然后,notifyItemInserted(1),你会得到很好的插入动画。

NOTE: this approach may add complexity to your project and requires knowledge about multi-type recycler view. 注意:此方法可能会增加项目的复杂性,并需要有关多类型回收站视图的知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM