RecyclerView: Set scroll position so that item appears at the bottom of the view

Kirill Rakhman picture Kirill Rakhman · May 24, 2016 · Viewed 14.8k times · Source

I have a RecyclerView with a LinearLayoutManager that is backed by an adapter with items of different height. Is there a way to tell the RecyclerView to set the scroll position so that item X appears (more or less) exactly at the bottom of the screen?

I tried LinearLayoutManager.scrollToPosition() but this will position the item at the top of the view.

Answer

giannisj5 picture giannisj5 · Jul 4, 2016
MyAdapter mAdapter;
RecyclerView recyclerView;
List<ItemData> data = new ArrayList<>();
LinearLayoutManager llm = new LinearLayoutManager(this);

try this in OnCreate method

recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(llm);
llm.setStackFromEnd(true);
mAdapter = new MyAdapter(data, getApplication());
recyclerView.setAdapter(mAdapter);

and when you insert an item try this

mAdapter.notifyItemInserted(data.size() - 1);
llm.scrollToPosition(data.size() - 1);