init
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
package com.sw.dualscreen.adapter
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewbinding.ViewBinding
|
||||
|
||||
abstract class BaseViewHolder<B : ViewBinding, T>(val binding: B) :
|
||||
RecyclerView.ViewHolder(binding.root) {
|
||||
abstract fun bind(item: T)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.sw.dualscreen.adapter
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewbinding.ViewBinding
|
||||
|
||||
class GridRecyclerAdapter<T, B : ViewBinding>(
|
||||
private val itemList: List<T>,
|
||||
private val bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> B,
|
||||
private val bindHolder: (B, T) -> Unit,
|
||||
private val onItemClick: ((T) -> Unit)? = null
|
||||
) : RecyclerView.Adapter<BaseViewHolder<B, T>>() {
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<B, T> {
|
||||
val inflater = LayoutInflater.from(parent.context)
|
||||
val binding = bindingInflater(inflater, parent, false)
|
||||
return object : BaseViewHolder<B, T>(binding) {
|
||||
override fun bind(item: T) = bindHolder(binding, item)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: BaseViewHolder<B, T>, position: Int) {
|
||||
holder.bind(itemList[position])
|
||||
holder.itemView.setOnClickListener {
|
||||
onItemClick?.invoke(itemList[position])
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = itemList.size
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.sw.dualscreen.adapter
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.View
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
|
||||
/**
|
||||
* item间距
|
||||
*/
|
||||
class GridSpacingItemDecoration(
|
||||
private val spanCount: Int,
|
||||
private val spacing: Int,
|
||||
private val includeEdge: Boolean
|
||||
) : RecyclerView.ItemDecoration() {
|
||||
|
||||
override fun getItemOffsets(
|
||||
outRect: Rect,
|
||||
view: View,
|
||||
parent: RecyclerView,
|
||||
state: RecyclerView.State
|
||||
) {
|
||||
val position = parent.getChildAdapterPosition(view)
|
||||
val column = position % spanCount
|
||||
|
||||
if (includeEdge) {
|
||||
outRect.left = spacing - column * spacing / spanCount
|
||||
outRect.right = (column + 1) * spacing / spanCount
|
||||
if (position < spanCount) outRect.top = spacing
|
||||
outRect.bottom = spacing
|
||||
} else {
|
||||
outRect.left = column * spacing / spanCount
|
||||
outRect.right = spacing - (column + 1) * spacing / spanCount
|
||||
if (position >= spanCount) outRect.top = spacing
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user