// 1. Define a Base Data Class
sealed class MediaItem(
open val id: String,
open val name: String,
open val path: String,
open val dateAdded: Long,
open val size: Long
)
// 2. Define Child Data Classes
data class PhotoItem(
override val id: String,
override val name: String,
override val path: String,
override val dateAdded: Long,
override val size: Long,
val resolution: String // Additional property specific to photos
) : MediaItem(id, name, path, dateAdded, size)
data class VideoItem(
override val id: String,
override val name: String,
override val path: String,
override val dateAdded: Long,
override val size: Long,
val duration: Long // Additional property specific to videos
) : MediaItem(id, name, path, dateAdded, size)
//3. Create a Utility Function to Load Data
class MediaRepository {
fun fetchMediaItems(): List<MediaItem> {
val photo = PhotoItem(
id = "1",
name = "Photo1",
path = "/storage/photos/photo1.jpg",
dateAdded = System.currentTimeMillis(),
size = 2048,
resolution = "1080x720"
)
val video = VideoItem(
id = "2",
name = "Video1",
path = "/storage/videos/video1.mp4",
dateAdded = System.currentTimeMillis(),
size = 4096,
duration = 60000 // Duration in milliseconds
)
return listOf(photo, video)
}
}
// 4. Use in RecyclerView
class MediaAdapter(private val items: List<MediaItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val TYPE_PHOTO = 1
private const val TYPE_VIDEO = 2
}
override fun getItemViewType(position: Int): Int {
return when (items[position]) {
is PhotoItem -> TYPE_PHOTO
is VideoItem -> TYPE_VIDEO
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
TYPE_PHOTO -> PhotoViewHolder(inflater.inflate(R.layout.item_photo, parent, false))
TYPE_VIDEO -> VideoViewHolder(inflater.inflate(R.layout.item_video, parent, false))
else -> throw IllegalArgumentException("Invalid view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is PhotoViewHolder -> holder.bind(items[position] as PhotoItem)
is VideoViewHolder -> holder.bind(items[position] as VideoItem)
}
}
override fun getItemCount() = items.size
class PhotoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(photo: PhotoItem) {
// Bind photo data
}
}
class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(video: VideoItem) {
// Bind video data
}
}
}