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

RecyclerView 사용법 (1)

2020. 4. 22.

파일 구조

Model -> 데이더 타입 모델

ViewHolder -> viewholder 객체 생성

Adapter -> Adapter 객체 생성

Model, ViewHolder, Adapter 파일은 하나로 생성해도 된다.

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 = listOf(
            Model("사과",2500),
            Model("배",2000),
            Model("포도",5000)
        )

        val adapter = Adapter(list)

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

 

Model, ViewHolder, Adapter 코드

package com.example.myexam1

class Model (val name: String, val price: Int){
    override fun toString(): String {
        return name
    }
}
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<Model>): RecyclerView.Adapter<ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
        return ViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.containerView.textView.text = list[position].name
        holder.containerView.textView2.text = "${list[position].price}원"
    }
}