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.
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.
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.
What you need to do is to increase the height of the recycler view to a minimum height
which will allow scrolling and hide your first element (screen height + height of the first item)
. You can achieve this by adding a dummy element as the last element and setting it's height or you could also do this using padding/margins (Have not tried this).
This also needs to be done dynamically once the view is drawn (You can do it statically if you are aware of the sizes of each item beforehand - I will not recommend this method though).
Use an onGLobalLayoutListner
to get a callback
once the view is drawn, do your measurements here and update the height. Now the scroll with offset should work fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.