0

New to Android development and Kotlin. I’m hoping to use different views based on the properties of my data class, but I’m not really sure how and I’m uncertain if what I want to do is even possible. I know I need to override getItemViewType, and leverage that in onCreateViewHolder, but I’m confused with the code for getItemViewType.

Room Data Class

data class PersonMessages(
        @Embedded
        val Person: Person,
        @Relation(
                parentColumn = "id",
                entityColumn = "person_id"
        )
        val Messages: List<Messages>
)

RecyclerView Adapter

class PeopleViewAdapter: ListAdapter<PersonMessages, PeopleViewAdapter.ViewHolder>(PeopleDiffCallback()) {
//    ...
override fun getItemViewType(position: Int): Int =
        when (getItem(position)) {
            is Messages -> R.layout.fragment_message_detail
            is Person -> R.layout.fragment_people_detail
            else -> throw IllegalStateException("Illegal item view type")
        }
}

For getItemViewType, Android Studio correctly complains that Messages and Person are Incompatible types with PersonMessages, but I have no idea as to what I need to change, and where, to get this to work.

All clue sticks appreciated.

Bink
  • 1,934
  • 1
  • 25
  • 41

1 Answers1

0

I chose to address this by transforming the data in the ViewModel into a list of the embedded classes. While I’m still not certain if this is the best direction, and would appreciate some commentary here, the relevant changes are below.

class MainViewModel(private val repository: DataRepository) : ViewModel() {
    //...

    init {
        _people = Transformations.map(repository.livePeopleMessages()) { peopleWithMessages ->
            peopleWithMessages.flatMap {
                mutableListOf<Any>(it.Person).also { personWithMessages ->
                    personWithMessages.addAll(it.Messages)
                }
            }
        }
    }
//...
}

class PeopleViewAdapter: ListAdapter<Any, RecyclerView.ViewHolder>(PeopleDiffCallback()) {//...}
Bink
  • 1,934
  • 1
  • 25
  • 41