코틀린

[코틀린] 리사이클러뷰

아스키의 공부방 2020. 12. 11. 21:58
728x90
반응형
class NoteList (var title: String, var contents: String) {

}

 

class NoteAdapter(private val items : List<NoteList>) :
    RecyclerView.Adapter<NoteAdapter.ViewHolder>()  {

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        val listener = View.OnClickListener {
            Toast.makeText(it.context, "클릭 : ${item.title}", Toast.LENGTH_SHORT).show()
        }
        holder.apply {
            bind(listener, item)
            itemView.tag = item
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflatedView = LayoutInflater.from(parent.context)
            .inflate(R.layout.layout_recyclerview, parent, false)

        return ViewHolder(inflatedView)
    }

    class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
        private var view: View = v
        fun bind(listener: View.OnClickListener, item: NoteList) {
            val title: TextView = view.findViewById(R.id.textView_title_recyclerView)
            val contents: TextView = view.findViewById(R.id.textView_contents_recyclerView)

            title.text = item.title
            contents.text = item.contents

            view.setOnClickListener(listener)
        }
    }

}

 

728x90
반응형