ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] RecyclerView
    카테고리 없음 2024. 4. 9. 14:43

    무엇인가?

    ListView의 상위호환으로 여러 아이템의 View를 재사용하며 스크롤 가능한 화면을 만든다.


    같이 사용하는 기능

    • Adapter
      • 데이터와 RecyclerView 사이를 연결하기 위해 존재하는 객체이다.
    • ViewHolder
      • 화면에 표시될 데이터를 저장하는 역할이다.
      • 스크롤해서 보이지 않는 View를 재활용하기 위해 해당 View를 기억하는 객체입니다.

    사용법

    <!-- activity_main.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"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/descriptionRecyclerView"
            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" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    <!-- item_description.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">
    
        <TextView
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="내용"
            android:textColor="@color/black"
            android:textSize="20sp"/>
    </LinearLayout>
    class DescriptionAdapter(
        private val descriptions: List<String>
    ) : RecyclerView.Adapter<DescriptionAdapter.Holder>() {
    
        // View의 정보를 담고 있는 RecyclerView.ViewHolder를 상속하는 클래스다.
        inner class Holder(binding: ItemDescriptionBinding) : RecyclerView.ViewHolder(binding.root) {
            val description = binding.description
        }
        
        // 여기서 View를 담고 있는 Holder를 생성해준다.
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
            val binding = ItemDescriptionBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return Holder(binding)
        }
        
        // 각 View가 보일 때 어떤 작업을 할지 적는 곳이다.
        // 필자는 description의 text를 바꾸어 주었다.
        override fun onBindViewHolder(holder: Holder, position: Int) {
            holder.description.text = descriptions[position]
        }
    
        override fun getItemId(position: Int): Long {
            return position.toLong()
        }
    
        override fun getItemCount(): Int {
            return descriptions.size
        }
    }
    class MainActivity : AppCompatActivity() {
    
        private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(binding.root)
            val descriptions = (1..50).map { "${it}번째 설명입니다." }
            binding.descriptionRecyclerView.apply {\
                // 위에서 만든 DescriptionAdapter를 descriptionRecyclerView의 adapter에 연결해주어야 한다.
                adapter = DescriptionAdapter(descriptions)
                // 레이아웃 매니저를 지정해주어야 한다.
                // 필자는 세로로 보이게 하고 싶기 때문에 LinearLayoutManager를 사용하였다.
                layoutManager = LinearLayoutManager(this@MainActivity)
            }
        }
    }

Designed by Tistory.