Skip to content

Commit

Permalink
chore: opt LayoutManager code
Browse files Browse the repository at this point in the history
  • Loading branch information
sinyu1012 committed Nov 17, 2021
1 parent d3cbf5a commit 56f20d5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,46 @@ class SquareLayoutManager @JvmOverloads constructor(
private val horizontalMinOffset: Float
get() = if (childWidth == 0) 0f else (width - childWidth) / 2f

var isAutoSelect = true
private var selectAnimator: ValueAnimator? = null

/**
* 初始化布局的时候,是否是定位到中心的 item
* 使用 SnapHelper 自动选中最靠近中心的 Item,默认为true
*/
var isAutoSelect = true

/**
* 初始化布局的时候,是否定位到中心的 Item
*/
var isInitLayoutCenter = true
private var isFirstLayout = true

private var lastSelectedPosition = 0
private var onItemSelectedListener: (Int) -> Unit = {}

/**
* 滑动到指定位置
*/
fun smoothScrollToPosition(position: Int) {
if (position > -1 && position < itemCount) {
startValueAnimator(position)
}
}

/**
* 滑动到中心
*/
fun smoothScrollToCenter() {
val centerPos = rowCount / 2 * spanCount + spanCount / 2
smoothScrollToPosition(centerPos)
}

/**
* 设置选中 Item 的监听回调
*/
fun setOnItemSelectedListener(listener: (Int) -> Unit) {
onItemSelectedListener = listener
}

override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
return RecyclerView.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT,
Expand Down Expand Up @@ -327,17 +355,6 @@ class SquareLayoutManager @JvmOverloads constructor(
return childWidth * (targetPos % spanCount) - horizontalOffset.toInt()
}

fun smoothScrollToPosition(position: Int) {
if (position > -1 && position < itemCount) {
startValueAnimator(position)
}
}

fun smoothScrollToCenter() {
val centerPos = rowCount / 2 * spanCount + spanCount / 2
smoothScrollToPosition(centerPos)
}

override fun smoothScrollToPosition(
recyclerView: RecyclerView?,
state: RecyclerView.State?,
Expand All @@ -346,9 +363,6 @@ class SquareLayoutManager @JvmOverloads constructor(
smoothScrollToPosition(position)
}

fun setOnItemSelectedListener(listener: (Int) -> Unit) {
onItemSelectedListener = listener
}

private fun startValueAnimator(position: Int) {
cancelAnimator()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt

class SquareSnapHelper : RecyclerView.OnFlingListener() {
internal class SquareSnapHelper : RecyclerView.OnFlingListener() {

private var mVerticalHelper: OrientationHelper? = null
private var mHorizontalHelper: OrientationHelper? = null
Expand Down

0 comments on commit 56f20d5

Please sign in to comment.