I am displaying a carousel within a RecyclerView. I implemented this carousel using ViewPager2. So the requirement is that the carousel should have no padding/margins and thus extend all the way to edge of the screen. However when displaying the first or last item, there should be a bit of whitespace to the left or right respectively. I've achieved that requirement using ItemDecoration
applied to the ViewPager2:
class CustomItemDecoration(
private val leftMargin: Int,
private val rightMargin: Int,
private val firstLastMargin: Int,
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect, view: View,
parent: RecyclerView, state: RecyclerView.State
) {
val position = parent.getChildAdapterPosition(view)
with(outRect) {
right = rightMargin
left = leftMargin
if (position == 0) {
left += firstLastMargin
} else if (position == state.itemCount - 1) {
right += firstLastMargin
}
}
}
}
However, this has caused the first and last item layouts suddenly having extra whitespace at the bottom. I do not understand why this is the case. Please see the following picture of the first item and the second item, note the whitespace present in the first item that is encircled:
My item layout looks like this:
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I have seen this question and while it's similar, I do not understand how the accepted answer fixes the issue? How to resolve this issue?
just use android:scaleType in AppCompatImageView
to