RoomsAdapter.kt 2.51 KB
Newer Older
1 2 3 4 5
package chat.rocket.android.chatrooms.adapter

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.R
6
import chat.rocket.android.chatrooms.adapter.model.RoomUiModel
7 8
import chat.rocket.android.util.extensions.inflate

9 10
class RoomsAdapter(private val listener: (RoomUiModel) -> Unit) :
    RecyclerView.Adapter<ViewHolder<*>>() {
11 12 13 14 15 16 17 18 19 20 21 22

    init {
        setHasStableIds(true)
    }

    var values: List<ItemHolder<*>> = ArrayList(0)
        set(items) {
            field = items
            notifyDataSetChanged()
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder<*> {
23 24 25 26 27 28 29 30 31 32 33 34 35 36
        return when (viewType) {
            VIEW_TYPE_ROOM -> {
                val view = parent.inflate(R.layout.item_chat)
                RoomViewHolder(view, listener)
            }
            VIEW_TYPE_HEADER -> {
                val view = parent.inflate(R.layout.item_chatroom_header)
                HeaderViewHolder(view)
            }
            VIEW_TYPE_LOADING -> {
                val view = parent.inflate(R.layout.item_loading)
                LoadingViewHolder(view)
            }
            else -> throw IllegalStateException("View type must be either Room, Header or Loading")
37 38 39 40 41 42 43
        }
    }

    override fun getItemCount() = values.size

    override fun getItemId(position: Int): Long {
        val item = values[position]
44
        return when (item) {
45
            is RoomItemHolder -> item.data.id.hashCode().toLong()
46
            is HeaderItemHolder -> item.data.hashCode().toLong()
47 48
            is LoadingItemHolder -> "loading".hashCode().toLong()
            else -> throw IllegalStateException("View type must be either Room, Header or Loading")
49 50 51 52
        }
    }

    override fun getItemViewType(position: Int): Int {
53
        return when (values[position]) {
54 55 56 57
            is RoomItemHolder -> VIEW_TYPE_ROOM
            is HeaderItemHolder -> VIEW_TYPE_HEADER
            is LoadingItemHolder -> VIEW_TYPE_LOADING
            else -> throw IllegalStateException("View type must be either Room, Header or Loading")
58 59 60 61 62 63 64 65 66 67 68
        }
    }

    override fun onBindViewHolder(holder: ViewHolder<*>, position: Int) {
        if (holder is RoomViewHolder) {
            holder.bind(values[position] as RoomItemHolder)
        } else if (holder is HeaderViewHolder) {
            holder.bind(values[position] as HeaderItemHolder)
        }
    }

69 70 71 72 73
    companion object {
        const val VIEW_TYPE_ROOM = 1
        const val VIEW_TYPE_HEADER = 2
        const val VIEW_TYPE_LOADING = 3
    }
74
}