Last active
June 12, 2022 06:59
-
-
Save hieuwu/16c25d0f5dd52ab6f6d30d7219bde22a to your computer and use it in GitHub Desktop.
Multiple view types in RecyclerView - Naive approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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