Skip to content

Instantly share code, notes, and snippets.

@hieuwu
Last active June 12, 2022 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hieuwu/16c25d0f5dd52ab6f6d30d7219bde22a to your computer and use it in GitHub Desktop.
Save hieuwu/16c25d0f5dd52ab6f6d30d7219bde22a to your computer and use it in GitHub Desktop.
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