본문 바로가기
🖥 Programming/📱 Android (Kotlin)

[Android] RecyclerView (리사이클러뷰) 알아보기

by MinChan-Youn 2021. 10. 22.

이번에는 kotlin으로 RecyclerView와 Binding에 대해서 알아보겠습니다~! :)

 

Step 1. Recyclerview 라이브러리 / Binding 설정 (주석부분 참고)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.recyclerview_kotlin"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

        //Binding 설정
        buildFeatures{
            viewBinding true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //recyclerview implementation
    implementation "androidx.recyclerview:recyclerview:1.2.1"
}

 

 

 

Step 2. RecyclerView코드  및 binding 설정

//MainActivity.kt
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val dataset: MutableList<rv_item> = arrayListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //바인딩 초기화
        binding = ActivityMainBinding.inflate(layoutInflater);

        //레이아웃(root뷰) 표시
        setContentView(binding.root);

        addData()

        binding.rvRecyclerview.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rvRecyclerview.adapter = RvAdapter(dataset)

    }

    private fun addData() {
        for (i in 0..99) {
            dataset.add(rv_item("$i th Name", "$i th Num"))
        }
    }
}
//RvAdapter.kt
class RvAdapter(private val items: MutableList<rv_item>) :
    RecyclerView.Adapter<RvAdapter.Holder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvAdapter.Holder {
        val binding = RvItemRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return Holder(binding)
    }

    override fun onBindViewHolder(holder: RvAdapter.Holder, position: Int) {
        holder.bind(items[position])
    }

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

    class Holder(private val binding: RvItemRowBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(data: rv_item) {
            binding.tvName.text = "Name: ${data.name}"
            binding.tvNum.text = "Num: ${data.num}"
        }
    }
}
//rv_item.kt
data class rv_item(
    val name: String,
    val num: String
)
<!-- activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>
<!-- rv_item_row.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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="name"
        android:textSize="20dp"
        android:layout_gravity="center_vertical"
        android:gravity="center_vertical"
        android:textStyle="bold"
        android:background="#F0F0F0"/>

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="num"
        android:textSize="20dp"
        android:layout_gravity="center_vertical"
        android:gravity="center_vertical"
        android:layout_marginBottom="10dp"
        android:textStyle="bold"
        android:background="#F0F0F0"/>

</LinearLayout>