Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical scroll the RecyclerView in Android by pixels

In my chat app I use RecyclerView and LayoutManager for showing chat messages list. I have a case when user browse old messages and new message arrives. At that point I want to scroll chat by small distance to acknowledge user of received new message. I need to scroll my RecyclerView by distance in pixels. I found that LayoutManager has method scrollVerticallyBy(),

public int scrollVerticallyBy (int dy, RecyclerView.Recycler recycler, RecyclerView.State state)

But I got confused by parameters it requires, RecyclerView.Recycler recycler, RecyclerView.State state and I am not sure if it will do my job.

In other words, I want to find replacement for ListView.smoothScrollBy(int distance, int duration)

like image 341
Rafael Avatar asked May 15 '15 09:05

Rafael


1 Answers

The best way to achieve this is using this:

recyclerView.smoothScrollBy(0, 100);

This is the signature of the method. You can scroll in x and y axis:

public void smoothScrollBy(int dx, int dy)

Note: If smothScrollBy(dx,dy) does not work is due to the RecyclerView has not been already loaded with its elements. For that I would recomend using:

new Handler().postDelayed(new Runnable() {
  @Override public void run() {
    recyclerView.smoothScrollBy(0, 100);
  }
}, 200);

In that way, you can be sure that the views have been loaded

like image 87
Antonio Avatar answered Oct 19 '22 23:10

Antonio