使用R类的好方法

时间:2017-10-29 17:24:26

标签: android android-recyclerview recycler-adapter

最近,我正在重构我的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()代码的可读性和可维护性?

1 个答案:

答案 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))
        }
    }
}