Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / adapter / HistoryRecyclerAdapter.kt
package jackall.moncalc.adapter

import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import jackall.moncalc.R
import jackall.moncalc.databinding.HistoryListItemBinding
import jackall.moncalc.viewmodel.HistoryItemViewModel
import jackall.moncalc.vo.HistoryItem

/**
 * Created by matsumoto_k on 2017/11/03.
 */
class HistoryRecyclerAdapter(var context: Context) : RecyclerView.Adapter<HistoryRecyclerAdapter.ViewHolder>() {

    var items: ArrayList<HistoryItem> = ArrayList()

    inner class ViewHolder(itemView: View, viewModel: HistoryItemViewModel) : RecyclerView.ViewHolder(itemView) {
        var viewModel: HistoryItemViewModel? = null

        init {
            this.viewModel = viewModel
        }

        fun loadItem(item: HistoryItem) {
            viewModel?.loadItem(item)
        }
    }

    fun setItemAndRefresh(items: ArrayList<HistoryItem>) {
        this.items = items
        notifyDataSetChanged()
    }

    fun getItemAt(position: Int): HistoryItem {
        return items.get(position)
    }

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        val item = getItemAt(position)
        holder?.loadItem(item)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        val binding = DataBindingUtil.inflate<HistoryListItemBinding>(LayoutInflater.from(context), R.layout.history_list_item, parent, false)
        binding.historyItemViewModel = HistoryItemViewModel()
        return ViewHolder(binding.root, binding.historyItemViewModel!!)
    }

    override fun getItemCount(): Int {
        return items.size
    }
}