안드로이드 개발

간단 RecyclerView 예제(kotlin)

최돌프 2022. 8. 10. 10:04
반응형
RecyclerView 사용 예제(kotlin)

 

프로젝트 진행 시 RecyclerView를 사용할 때가 많아 간단히 정리해본다.

 

1. RecyclerView생성

-MainActivity.xml

<?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/db_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.247" />
        
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity에 RecyclerView를 생성해준다.

2. item 생성

-rv_item.xml

<?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">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="1dp"
        android:layout_marginTop="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginBottom="1dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <TextView
            android:id="@+id/rv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:text="TextView" />

        <TextView
            android:id="@+id/rv_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

app > res > layout 위치에 RecyclerView에 뿌려줄 item 생성 (rv_item.xml)

 

3. Adapter 생성
buildFeatures{
    viewBinding true
}

RecyclerView를 사용하려면 viewBinding을 먼저 설정해주어야 한다.

build.gradle (Module) 쪽에 코드를 작성해준다.

 

-RvListAdapter.kt

class RvListAdapter(var list : ArrayList<String>) : RecyclerView.Adapter<RvListAdapter.RvViewHolder>() {

    class RvViewHolder(binding: RvItemBinding) : RecyclerView.ViewHolder(binding.root)

    //뷰홀더 생성
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder {
        val binding = RvItemBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return RvViewHolder(binding)
    }

    //뷰홀더에 아이템 바인드 => RecyclerView에 보여줄 아이템 생성
    override fun onBindViewHolder(holder: RvViewHolder, position: Int) {
        holder.itemView.txt_name.text = list[position].name
        holder.itemView.txt_addr.text = list[position].addr

	//item간 간격 조절
        val layoutParams =holder.itemView.layoutParams
        layoutParams.height=100
        holder.itemView.requestLayout()
    }

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

패키지를 하나 만들어 넣어주면 보기가 더 편하다.(ex.  java > adapter )

 

*바인딩을 사용하면 xml의 이름에 주의해주어야 한다.

rv_item.xml이 바인딩을 사용할 땐 RvItemBindng으로 사용된다.

앞글자가 대문자로, _은 없어지고 그 뒤 앞글자가 대문자가 되는 형식.

 

4.RecyclerView 띄우기

 

class MainActivity : AppCompatActivity() {
    private lateinit var viewManager : RecyclerView.LayoutManager
    private lateinit var rvAdapter : RvListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
            
        val arr = ArrayList<String>()
        arr?.add("test")
        arr?.add("test1")
        arr?.add("test2")
            
        //rv_list에 Adapter를 사용해 list를 띄워준다.
        viewManager = LinearLayoutManager(this)
        rvAdapter = RvListAdapter(arr)
        rvAdapter.notifyDataSetChanged()
        rv_list.apply {
            layoutManager = viewManager
            adapter = rvAdapter
        }
    }
}

arr에 간단한 샘플들을 넣어준 뒤 Adapter를 이용하여 RecylcerView를 띄워 준다.

활용하기 나름이지만 RecyclerView를 사용하는데 공식? 틀? 같은 개념으로 개인적으로 사용하는 중입니다.

반응형