最近,我正在重构我的RecycelrView's Adapter
代码。此时它看起来像这样:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val inflater = LayoutInflater.from(parent.context)
when (viewType) {
TransportListData.HEADER_TYPE -> {
val headerView = inflater.inflate(R.layout.holder_header, parent, false)
return HeaderHolder(headerView)
}
TransportListData.ROUTE_TYPE -> {
val routeView = inflater.inflate(R.layout.holder_route, parent, false)
return RouteHolder(routeView)
}
TransportListData.STOP_TYPE -> {
val busStopView = inflater.inflate(R.layout.holder_bus_stop, parent, false)
return StopHolder(busStopView)
}
else -> throw IllegalArgumentException("viewType returned unexpected type: $viewType")
}
}
现在我想知道如何改进它。我想出了将viewType
的常量值从随机数更改为R.layout
的常量的想法。所以代码看起来像这样:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(viewType, parent, false)
return when (viewType) {
TransportListData.HEADER_TYPE -> HeaderHolder(view)
TransportListData.ROUTE_TYPE -> RouteHolder(view)
TransportListData.STOP_TYPE -> StopHolder(view)
else -> throw IllegalArgumentException("viewType returned unexpected type: $viewType")
}
}
现在,我想知道您对此的看法。使用R
类中的常量是否合适,特别是在单元测试时?如何在没有任何库的情况下提高onCreateViewHolder()
代码的可读性和可维护性?
答案 0 :(得分:1)
我通常会在我的create
类中添加静态ViewHolder
(或其他)方法,这会将创建持有者的责任从适配器本身转移到ViewHolder
类
class MyViewHolder(itemView: View): ViewHolder(itemView) {
companion object {
const val layout = R.layout.item_layout
fun create(parent: ViewGroup): MyViewHolder {
return MyViewHolder(layoutInflater.inflate(layout, parent, false))
}
}
}