본문 바로가기

Android/개념

RecyclerView

1. activity_main.xml 

- reclerview 선언하기

 

<?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/mainRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

2. recycler_item.xml 만들기

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp">

    <TextView
        android:id="@+id/recyclerItem"
        android:text="안녕"
        android:textSize="20dp"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.appcompat.widget.LinearLayoutCompat>

 

3. RecyclerAdapter(어댑터 만들기)

 

class RecyclerAdapter(val items : MutableList<String>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {

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

        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerAdapter.ViewHolder, position: Int) {
        // 뷰바인딩해줌
        holder.bindItems(items[position])
    }

    // 전체 리사이클러뷰의 갯수
    override fun getItemCount(): Int {
        return items.size
    }

    // ViewHolder를 만들어 줘야함
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(item : String) {
           val recycler_text = itemView.findViewById<TextView>(R.id.recyclerItem)
           recycler_text.text = item
        }
    }

}

 

4. MainActivity

 

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

        // items에 데이터를 생성함
        val items = mutableListOf<String>()

        items.add("A")
        items.add("B")
        items.add("C")

        // 생성한 데이터를 어댑터에 넘겨주기
        val recyclerAdapter = RecyclerAdapter(items)

        // 우리가 만든 RecyclerView 찾기
        val recycle = findViewById<RecyclerView>(R.id.mainRecyclerView)

        // 어탭터 연결해주기
        recycle.adapter = recyclerAdapter

        recycle.layoutManager = LinearLayoutManager(this)

    }
}