Chris Blank
Chris Blank

Reputation: 213

Adding new item to the top of the RecyclerView

I am adding an item to recyclerview position 0 programamticly

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 ?

Upvotes: 21

Views: 19741

Answers (4)

j2esu
j2esu

Reputation: 1687

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. 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.

NOTE: this approach may add complexity to your project and requires knowledge about multi-type recycler view.

Upvotes: 3

Atiq
Atiq

Reputation: 14835

well you can use 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?

Upvotes: 21

Akshay Panchal
Akshay Panchal

Reputation: 695

Try this

mRecyclerView.smoothScrollToPosition(0);

Upvotes: 3

user5543258
user5543258

Reputation:

Yes, you can do this

mRecyclerView.smoothScrollToPosition(0);

Upvotes: 3

Related Questions