Newer
Older
DevRealm / app / src / main / java / jackall / devrealm / adapter / MainAdapter.kt
package jackall.devrealm.adapter

import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import jackall.devrealm.R
import jackall.devrealm.databinding.ListItemBinding
import jackall.devrealm.viewmodel.ItemViewModel

/**
 * Created by matsumoto_k on 2017/11/08.
 */
class MainAdapter(val context: Context, val items: ArrayList<ItemViewModel>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        val binding = DataBindingUtil.inflate<ListItemBinding>(LayoutInflater.from(context), R.layout.list_item, parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        holder?.binding?.itemViewModel = items.get(position)
    }

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

    fun insert(item: ItemViewModel) {
        items.add(item)
        notifyItemInserted(itemCount)
    }

    fun remove(position: Int) {
        items.removeAt(position)
        notifyItemRemoved(position)
    }

    inner class ViewHolder(val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root)
}