[kotlin] 리사이클러뷰에서 아이템에 동적 높이 조정하기

리사이클러뷰에서 아이템의 각 로우가 동적으로 자체 높이를 가지도록 하는 것은 종종 필요한 기능입니다. 이를 위해 아이템의 컨텐츠에 맞게 높이를 동적으로 조정하는 방법에 대해 다루겠습니다.

1. 아이템 레이아웃 조정

리사이클러뷰에서 아이템의 높이를 동적으로 조정하려면 아이템 레이아웃을 수정해야 합니다. 아이템의 루트 뷰에 wrap_content를 사용하여 높이를 설정하고 내부 컨텐츠는 match_parent로 설정합니다.

<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/titleTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/contentTextView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Content"
        android:textSize="14sp" />

</LinearLayout>

위 예제에서는 contentTextView의 높이를 match_parent로 설정하여 내부 컨텐츠에 따라 동적으로 높이를 조정하도록 했습니다.

2. 아이템 높이 계산

리사이클러뷰 어댑터에서 onBindViewHolder 메서드 내부에서 아이템의 높이를 계산하고 설정해야 합니다.

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val item = itemList[position]
    holder.titleTextView.text = item.title
    holder.contentTextView.text = item.content

    holder.itemView.post {
        val height = holder.titleTextView.height + holder.contentTextView.height
        holder.itemView.layoutParams.height = height
    }
}

위 예제에서는 post 메서드를 사용하여 아이템의 높이를 레이아웃에 적용하고 있습니다.

이제 아이템의 레이아웃을 조정하고, 어댑터에서 아이템 높이를 동적으로 계산하여 설정함으로써 리사이클러뷰 아이템의 높이를 동적으로 조정할 수 있게 되었습니다.

이러한 방식은 리사이클러뷰 아이템의 내부 컨텐츠에 따라 동적으로 높이를 조정해야 할 때 유용하게 사용될 수 있습니다.

이제 실제 데이터와 함께 위의 코드를 적용해 보시기 바랍니다.

참고 자료