안드로이드(Kotlin)/기초/

RecyclerView 사용법 (2)

2020. 4. 22.

파일 구조

ViewHolder -> viewholder 객체 생성

Adapter -> adapter 객체 생성

bg_item.xml -> 아이템 선택시 화면 변경

item.xml -> viewholder 객체 view

 

컴포넌트 트리

RecyclerView -> id: listView

 

item.xml 컴포넌트 트리

 

코드

package com.example.myexam1

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val list = (0..100).toList().shuffled()

        val adapter = Adapter(list)

        adapter.onItemSelectionListener ={
            println("$it")
        }

        listView.adapter = adapter
        listView.layoutManager = LinearLayoutManager(this)
    }
}

 

bg_item.xml, ViewHolder, Adapter 코드

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_light"/>
    <item android:drawable="@android:color/white"/>
</selector>
package com.example.myexam1

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer

class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer
package com.example.myexam1

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item.view.*

class Adapter (private val list:List<Int>): RecyclerView.Adapter<ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
        view.setOnClickListener { v ->
            val id = v?.tag
            if(selectionList.contains(id)) selectionList.remove(id)
            else selectionList.add(id as Long)
            notifyDataSetChanged()
            onItemSelectionListener?.let{it(selectionList)}
        }
        return ViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.containerView.textView.text = list[position].toString()
        holder.containerView.tag = getItemId(position)
        holder.containerView.isActivated = selectionList.contains(getItemId(position))
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    val selectionList = mutableListOf<Long>()
    var onItemSelectionListener: ((MutableList<Long>)->Unit)? = null
}