Two inner classes within a RecyclerView class to display different layouts

44 Views Asked by At

I am trying to declare two inner classes within a RecyclerView class using Kotlin. Currently, when I try this like below, I get an error message on both classes. What do I need to change to make this work on Kotlin?

    class ChatAdapter(private val dataSet: ArrayList<ChatMessage>, private val receiverProfilImage: Bitmap,val senderId:String) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {


     class SentMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
     {
         lateinit var binding: ItemContainerSentMessageBinding

         SentMessageViewHolder(itemContainerSentMessageBinding: ItemContainerSentMessageBinding)  {
             binding = itemContainerSentMessageBinding
         }

         fun setData(chatMessage: ChatMessage)
         {
             binding.textMessage.text = chatMessage.message
             binding.textDateTime.text = chatMessage.dateTime
         }
     }


     class ReceivedMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
     {
         lateinit var binding: ItemContainerReceivedMessageBinding

         ReceivedMessageViewHolder(itemContainerReceivedMessageBinding: ItemContainerReceivedMessageBinding) {
             binding = itemContainerReceivedMessageBinding
         }

         fun setData(chatMessage: ChatMessage,receiverProfilImage:Bitmap)
         {
             binding.textMessage.text = chatMessage.message
             binding.textDateTime.text = chatMessage.dateTime
             binding.imageProfil.setImageBitmap(receiverProfilImage)
         }

     ...
     }

Expecting member declaration

1

There are 1 best solutions below

0
Tenfour04 On

It looks like you're trying to declare secondary constructors of these classes using a syntax that is sort of like Java constructor syntax.

You don't need secondary constructors anyway, since the only way you want to instantiate one of these is by using a view binding. (So, you can look at the Kotlin documentation to learn how to write a secondary constructor. I won't explain it here since you don't need it in this case.)

There is no reason to use lateinit for a property that can be initialized during construction time. In this case, it can just be a property declared in your primary constructor. The root view of the binding is the base view of your ViewHolder, so you can pass binding.root to the superclass constructor.

 class SentMessageViewHolder(val binding: ItemContainerSentMessageBinding) : RecyclerView.ViewHolder(binding.root)
 {
     fun setData(chatMessage: ChatMessage)
     {
         binding.textMessage.text = chatMessage.message
         binding.textDateTime.text = chatMessage.dateTime
     }
 }