KOTLIN

코틀린(Kotlin) 리사이클러뷰 사용하기

사과씨앗 2021. 1. 10. 19:28
728x90
반응형

안녕하세요 이번 글에서는 리사이클 러뷰를 사용해보겠습니다.

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

먼저 activity_main.xml에 위처럼 recyclerview를 추가하여 줍니다.

 

 

다음은 하나하나의 아이템이 들어갈 layout을 만들어 주기 위해 item_recycler.xml을 하나 만들어 줍니다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">


    <TextView
        android:id="@+id/tv_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="01" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:text="Title" />

    <TextView
        android:id="@+id/tv_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="date" />
</LinearLayout>

 

위처럼 코딩하여 주면

 

이런 모양으로 layout이 생성됩니다.

 

이제 들어갈 데이터 객체를 만들어 주기 위해 클래스를 Memo라는 클래스를 하나 만들어 주겠습니다.

 

 

package com.example.recyclerview


data class Memo(var no:Int , var title:String , var timestamp:Long) {
    
}

간단하게 생성자를 하나 만들어 줍니다.

 

그다음 Adapter을 만들어 주기 위해 MemoAdapter클래스를 하나 생성하여 줍니다.

package com.example.recyclerview

import android.icu.text.SimpleDateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_recycler.view.*

//RecyclerView.Adapter 상속받은 다음 <> 안에 holder 객체를 받아 줍니다.
class MemoAdapter(val listData:ArrayList<Memo>): RecyclerView.Adapter<holder>() {
    //반복될 layout의 target을 지정하여 준다음 holder로 보내어 줍니다.
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_recycler,parent,false)
        return holder(view)
    }
 
    //리스트의 데이터를 하나씩 꺼내어 holder에 넣어 줍니다.
    override fun onBindViewHolder(holder: holder, position: Int) {
        val memo = listData.get(position)
        holder.setMemo(memo)
    }
    //리스트의 사이즈를 반환하여 줍니다.
    override fun getItemCount(): Int {
        return listData.size
    }
}

//onBindViewHolder에서 전달받은 데이터를 layout에 자리에 맞게 데이터를 대입하여 줍니다.
class holder(itemView: View):RecyclerView.ViewHolder(itemView){
    fun setMemo(memo: Memo){
         itemView.tv_no.text = memo.no.toString()
         itemView.tv_title.text = memo.title.toString()

        var sdf = SimpleDateFormat("yyy/MM/dd")
        var formattedDate = sdf.format(memo.timestamp)
        itemView.tv_date.text = formattedDate
        itemView.tv_date
    }


}

 

마지막으로 MainActivity를 코딩하여 줍시다.

package com.example.recyclerview

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 data:ArrayList<Memo> = loadData()
        //데이터를 담은 list를 Adapter로 전달 합니다.
        var adapter = MemoAdapter(data)
        //activity_main.xml에 만들어 놓은 recyclerView의 아이디를 가져온 다음 adapter을 지정하여 줍니다.
        recyclerView.adapter = adapter
        //마지막으로 recyclerView를 화면에 보여주는 형태를 결정하는 레이아웃 매니저를 연결합니다.
        recyclerView.layoutManager = LinearLayoutManager(this)

    }

    //데이터를 리스트 형식으로 만들어 주기위한 함수
    fun loadData():ArrayList<Memo>{
        //제네릭을 Memo로 설정한 리스트 초기화
        val data:ArrayList<Memo> = arrayListOf()

        //반복문을 이용하여 리스트에 데이터 추가
        for(no in 1..100){
            var title = "${no} 번째 타이틀 입니다."
            var date = System.currentTimeMillis()

            var memo = Memo(no,title,date)
            data.add(memo)
        }
        //리스트 반환
        return data
    }

}

이제 실행시켜 보면

 

다음과 같이 만들어 놓은 리스트가 정상적으로 출력되는 것을 확인할 수 있습니다.

 

package com.example.recyclerview

import android.icu.text.SimpleDateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_recycler.view.*

//RecyclerView.Adapter 상속받은 다음 <> 안에 holder 객체를 받아 줍니다.
class MemoAdapter(val listData:ArrayList<Memo>): RecyclerView.Adapter<holder>() {
    //반복될 layout의 target을 지정하여 준다음 holder로 보내어 줍니다.
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_recycler,parent,false)
        //클릭이벤트를 넣어 줍시다.
        return holder(view).apply {
            itemView.setOnClickListener {
            val curpos : Int = adapterPosition
            val memo: Memo = listData.get(curpos)
            var sdf = SimpleDateFormat("yyy/MM/dd")
            var formattedDate = sdf.format(memo.timestamp)

            Toast.makeText(parent.context,"${memo.no}  \n${memo.title} \n${formattedDate}",Toast.LENGTH_SHORT).show()
              }
            }
        }


    //리스트의 데이터를 하나씩 꺼내어 holder에 넣어 줍니다.
    override fun onBindViewHolder(holder: holder, position: Int) {
        val memo = listData.get(position)
        holder.setMemo(memo)
    }
    //리스트의 사이즈를 반환하여 줍니다.
    override fun getItemCount(): Int {
        return listData.size
    }
}

//onBindViewHolder에서 전달받은 데이터를 layout에 자리에 맞게 데이터를 대입하여 줍니다.
class holder(itemView: View):RecyclerView.ViewHolder(itemView){
    fun setMemo(memo: Memo){
         itemView.tv_no.text = memo.no.toString()
         itemView.tv_title.text = memo.title.toString()

        var sdf = SimpleDateFormat("yyy/MM/dd")
        var formattedDate = sdf.format(memo.timestamp)
        itemView.tv_date.text = formattedDate
        itemView.tv_date
    }


}

onCreateViewHolder에서 holder리턴시 위처럼 클릭 이벤트를 넣어주면 해당 리스트의 포지션에 맞게 값을 불러올 수 있습니다.

 

오늘도 봐주셔서 감사합니다.

728x90
반응형