suyu/src/android/app/src/main/java/org/suyu/suyu_emu/layout/AutofitGridLayoutManager.kt
Exverge 4106a59d8f
Some checks failed
suyu-ci / Check REUSE Specification (push) Failing after 13s
codespell / Check for spelling errors (push) Has been cancelled
suyu verify / Verify Format (push) Has been cancelled
suyu verify / test build (linux-fresh, clang) (push) Has been cancelled
suyu verify / test build (linux-fresh, linux) (push) Has been cancelled
suyu verify / test build (linux-mingw, windows) (push) Has been cancelled
suyu verify / android (push) Has been cancelled
Add suyu copyright notice in files with modifications
Would've been nice to know [skip ci] was on Forgejo >1.21 only
2024-03-23 19:09:45 -04:00

64 lines
2.1 KiB
Kotlin

// SPDX-FileCopyrightText: 2023 yuzu Emulator Project 2023 yuzu Emulator Project 2024 suyu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
package org.suyu.suyu_emu.layout
import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import org.suyu.suyu_emu.R
/**
* Cut down version of the solution provided here
* https://stackoverflow.com/questions/26666143/recyclerview-gridlayoutmanager-how-to-auto-detect-span-count
*/
class AutofitGridLayoutManager(
context: Context,
columnWidth: Int
) : GridLayoutManager(context, 1) {
private var columnWidth = 0
private var isColumnWidthChanged = true
private var lastWidth = 0
private var lastHeight = 0
init {
setColumnWidth(checkedColumnWidth(context, columnWidth))
}
private fun checkedColumnWidth(context: Context, columnWidth: Int): Int {
var newColumnWidth = columnWidth
if (newColumnWidth <= 0) {
newColumnWidth = context.resources.getDimensionPixelSize(R.dimen.spacing_xtralarge)
}
return newColumnWidth
}
private fun setColumnWidth(newColumnWidth: Int) {
if (newColumnWidth > 0 && newColumnWidth != columnWidth) {
columnWidth = newColumnWidth
isColumnWidthChanged = true
}
}
override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State) {
val width = width
val height = height
if (columnWidth > 0 && width > 0 && height > 0 &&
(isColumnWidthChanged || lastWidth != width || lastHeight != height)
) {
val totalSpace: Int = if (orientation == VERTICAL) {
width - paddingRight - paddingLeft
} else {
height - paddingTop - paddingBottom
}
val spanCount = 1.coerceAtLeast(totalSpace / columnWidth)
setSpanCount(spanCount)
isColumnWidthChanged = false
}
lastWidth = width
lastHeight = height
super.onLayoutChildren(recycler, state)
}
}