如何在 Kotlin 中使用 sealed class 实现 ViewHolder
How to implement ViewHolder using sealed class in Kotlin
我在这条推文中看到了一个有趣的 viewholder 实现 https://twitter.com/AndroidDev/status/972502799496790018
override fun onBindViewHolder(holder: SealedAdapterViewHolder, position: Int) {
return when (holder) {
is HeaderHolder -> holder.displayHeader(items[position])
is DetailsHolder -> holder.displayDetails(items[position])
}
}
不幸的是,我不知道如何实现 thouse holders。而且我没有找到这个技巧的任何例子。
在我的 viewholders 中,我必须扩展 RecyclerView.ViewHolder 并且我必须扩展 sealed class 以便我可以在 "when clauses" 中使用它。不允许多重继承。
那么这可能吗?如果可能的话怎么办?
P.S.
原作者这样写:
You can also use sealed classes in a RecyclerView adapter. They’re a
perfect fit for ViewHolders - with a clean set of types to dispatch
explicitly to each holder. Used as an expression, the compiler will
error if all types aren’t matched.
像这样:
sealed class SealedAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
class HeaderHolder(view: View) : SealedAdapterViewHolder(view)
class DetailsHolder(view: View) : SealedAdapterViewHolder(view)
}
它在线程的第一个 post 中。
fun foo(holder : SealedAdapterViewHolder){
when (holder) {
is HeaderHolder -> holder.displayHeader(items[position])
is DetailsHolder -> holder.displayDetails(items[position])
}
}
sealed class SealedAdapterViewHolder(view: View) : RecyclerView.ViewHolder(view)
data class HeaderHolder(val view: View): SealedAdapterViewHolder(view){
fun displayHeader(...){}
}
data class DetailsHolder(val view: View): SealedAdapterViewHolder(view){
fun displayDetails(...){}
}
我在这条推文中看到了一个有趣的 viewholder 实现 https://twitter.com/AndroidDev/status/972502799496790018
override fun onBindViewHolder(holder: SealedAdapterViewHolder, position: Int) {
return when (holder) {
is HeaderHolder -> holder.displayHeader(items[position])
is DetailsHolder -> holder.displayDetails(items[position])
}
}
不幸的是,我不知道如何实现 thouse holders。而且我没有找到这个技巧的任何例子。
在我的 viewholders 中,我必须扩展 RecyclerView.ViewHolder 并且我必须扩展 sealed class 以便我可以在 "when clauses" 中使用它。不允许多重继承。
那么这可能吗?如果可能的话怎么办?
P.S.
原作者这样写:
You can also use sealed classes in a RecyclerView adapter. They’re a perfect fit for ViewHolders - with a clean set of types to dispatch explicitly to each holder. Used as an expression, the compiler will error if all types aren’t matched.
像这样:
sealed class SealedAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
class HeaderHolder(view: View) : SealedAdapterViewHolder(view)
class DetailsHolder(view: View) : SealedAdapterViewHolder(view)
}
它在线程的第一个 post 中。
fun foo(holder : SealedAdapterViewHolder){
when (holder) {
is HeaderHolder -> holder.displayHeader(items[position])
is DetailsHolder -> holder.displayDetails(items[position])
}
}
sealed class SealedAdapterViewHolder(view: View) : RecyclerView.ViewHolder(view)
data class HeaderHolder(val view: View): SealedAdapterViewHolder(view){
fun displayHeader(...){}
}
data class DetailsHolder(val view: View): SealedAdapterViewHolder(view){
fun displayDetails(...){}
}