Problem description
LinearLayoutManager.scrollToPositionWithOffset(pos, 0)
works great if the sum of RecyclerView
's all children's height is big than screen height. But it does not work if the sum of RecyclerView
's all children's height is small than screen height.
Problem description in detail
Let's say I have an Activity
and a RecyclerView
as it's root view. RecyclerView
's width
and height
are both match_parent
. This RecyclerView
has 3 items and the sum of these 3 child view's height is small than screen height. I want to hide first item when Activity
is onCreated
. User will see second item at start. If user scroll down, he still can see first item. So I call LinearLayoutManager.scrollToPositionWithOffset(1, 0)
. But it won't work since the sum of RecyclerView
's all children's height is small than screen height.
Question
How can I make RecyclerView
scroll to specific position even though the sum of RecyclerView
's all children's height is small than screen height.
Following is my code according to @Haran Sivaram's answer:
Item first = new Item();
Item second = new Item();
Item third = new Item();
List<Item> list = Arrays.asList(first, second, three);
adapter.add(list);
adapter.notifyDataSetChanged();
recyclerView.post(new Runnable() {
@Override
public void run() {
int sumHeight = 0;
for (int i = 0; i < recyclerView.getChildCount(); i++) {
View view = recyclerView.getChildAt(i);
sumHeight += view.getHeight();
}
if (sumHeight < recyclerView.getHeight()) {
adapter.addItem(new VerticalSpaceViewModel(recyclerView.getHeight() - sumHeight + recyclerView.getChildAt(0).getHeight()));
}
linearLayoutManager.scrollToPositionWithOffset(1, 0);
}
});
It worked. But has some small issues.