Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple view types in RecyclerView - Naive approach
class WeatherItemAdapter :
ListAdapter<Weather, WeatherItemAdapter.WeatherItemViewHolder>(DiffCallback) {
// Other implementation for DiffCallback
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherItemViewHolder {
when (viewType) {
WeatherViewType.DAY.ordinal -> {
val view = LayoutInflater.from(parent.context).inflate(R.layout.weather_day_item, parent, false)
return WeatherDayItemViewHolder(view)
}
WeatherViewType.NIGHT.ordinal -> {
val view = LayoutInflater.from(parent.context).inflate(R.layout.weather_night_item, parent, false)
return WeatherNightItemViewHolder(view)
}
}
throw Exception("View not found")
}
override fun getItemViewType(position: Int): Int {
val weather = getItem(position)
if (isDayWeather(weather)) {
return WeatherViewType.DAY.ordinal
}
return WeatherViewType.NIGHT.ordinal
}
private fun isDayWeather(weather: Weather?): Boolean {
// Your implementation
return false
}
override fun onBindViewHolder(holder: WeatherItemViewHolder, position: Int) {
val weather = getItem(position)
holder.bind(weather)
}
enum class WeatherViewType(i: Int) {
NIGHT(1),
DAY(2)
}
}
class WeatherDayItemViewHolder(private var binding: View) :
WeatherItemViewHolder(binding) {
override fun bind(weather: Weather) {
// Implementation
}
}
class WeatherNightItemViewHolder(private var binding: View) :
WeatherItemViewHolder(binding) {
override fun bind(weather: Weather) {
// Implementation
}
abstract class WeatherItemViewHolder(private var binding: View) :
RecyclerView.ViewHolder(binding.root) {
open fun bind(weather: Weather) {
// Implementation
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment