I want to use RecyclerView
with GridLayoutManager
to achieve something like that:
Here is GridLayoutManager
with horizontal orientation and 2 rows. What's important for me here is that RecyclerView
is set as wrap_content
.
So I tried to achieve my goal with such code:
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val adapter = Adapter()
private val layoutManager = GridLayoutManager(this, 2, RecyclerView.HORIZONTAL, false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.adapter = adapter
recyclerView.layoutManager = layoutManager
adapter.submitList(listOf(Unit, Unit, Unit, Unit))
}
}
Adapter.kt
class Adapter : ListAdapter<Any, ItemHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(viewType, parent, false)
return ItemHolder(itemView)
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
}
override fun getItemViewType(position: Int): Int {
return when {
position % 2 == 0 -> R.layout.item_small
else -> R.layout.item_normal
}
}
class DiffCallback : DiffUtil.ItemCallback<Any>() {
override fun areItemsTheSame(oldItem: Any, newItem: Any) = false
override fun areContentsTheSame(oldItem: Any, newItem: Any) = false
}
class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
item_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="8dp"
android:background="@color/colorAccent" />
item_small.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_margin="8dp"
android:background="@color/colorAccent" />
Unfortunately as the result, each row stretches to the largest row in grid:
The question is how can I remove the spacing between first row and second row? Keep in mind that I have to have scrollable horizontal grid that its height depends on its content. And items have to have fixed size.