I tried to implement a carousel view with snapping. I add spacing to the cards in the recyclerview with itemdecorations, that add spacing between the cards and enough spacing to center the first and last item. When I now load the recyclerview, the recyclerview doesnt start with the first card centered. I tried to fix it with layoutmanager.scrollToPositionWithOffset, and it starts slightly less offset, but I can't get it to start at the beginning.
This is my onCreate where I load the recyclerview:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.coverList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(layoutManager);
Song song = new Song(null, "Test", "Test", 0, 0);
List<Song> songs = new ArrayList<>();
songs.add(song);
songs.add(song);
songs.add(song);
songs.add(song);
songs.add(song);
songs.add(song);
CoverRecyclerViewAdapter adapter = new CoverRecyclerViewAdapter(songs);
recyclerView.setAdapter(adapter);
int spacing = getResources().getDimensionPixelSize(R.dimen.carousel_spacing);
recyclerView.addItemDecoration(new CarouselItemDecoration(spacing));
new PagerSnapHelper().attachToRecyclerView(recyclerView);
}
This is my itemdecoration class:
public class CarouselItemDecoration extends RecyclerView.ItemDecoration {
private int innerSpacing;
public CarouselItemDecoration(@Px int innerSpacing) {
this.innerSpacing = innerSpacing;
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int itemPosition = parent.getChildAdapterPosition(view);
int itemWidth = view.getLayoutParams().width;
int offset = (parent.getWidth() - itemWidth) / 2;
if(itemPosition == 0) {
outRect.left = offset;
} else {
outRect.left = innerSpacing / 2;
}
if(itemPosition == state.getItemCount() - 1) {
outRect.right = offset;
} else {
outRect.right = innerSpacing / 2;
}
}
}
How can I load my recyclerview centered on the first card?
question from:
https://stackoverflow.com/questions/65926923/scrolltoposition-doesnt-work-with-recyclerview-in-a-horizontal-linearlayoutmanag 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…