【发布时间】:2018-05-28 17:17:31
【问题描述】:
我有RecyclerView 和Grid layout。一切正常。
但我需要将列设置在水平中心。例如。我有 18 个项目,跨度计数为 4。对于最后一行,我有 2 个项目。这两项应位于水平中心而不是左侧。
这是我的RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:overScrollMode="never"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
android:layout_gravity="center_horizontal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/rv_answer" />
这是我的adapter layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_marginStart="@dimen/marginVSmall"
android:layout_marginEnd="@dimen/marginVSmall"
android:layout_marginTop="@dimen/marginVSmall"
android:layout_marginBottom="@dimen/marginVSmall"
android:layout_height="wrap_content">
<curvegraph.com.vijay.widgets.SquareTextView
android:id="@+id/tv_option"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@drawable/circle"
android:gravity="center"
android:text="A"
android:textStyle="bold"
android:maxLength="1"
android:textColor="@color/colorWhite"
android:textSize="@dimen/textXLarge"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</android.support.constraint.ConstraintLayout>
我要设置的 Kotlin 代码LayoutManager
rv_option.layoutManager = GridLayoutManager(this, 4)
这是我的 Kotlin 代码:
val grid = GridLayoutManager(this, 8)
grid.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (position > 15) { // totalRowCount : How many item you want to show
2 // the item in position now takes up 4 spans
} else 1
}
}
rv_option.layoutManager=grid
rv_option.setHasFixedSize(true)
optionsAdapter.spanCountFun(8)
【问题讨论】:
-
能否提供您尝试的java代码。
标签: android android-recyclerview kotlin gridlayoutmanager