본문 바로가기
공부/안드로이드

RecyclerView에서 View추가

by 단순한 프로그래머 2025. 9. 11.

개발을 하다보면 리스트뷰에서 고정적으로 보여지는게 아닌

때에 따라서 리스트에서 뷰가 여러개 추가되는 형태를 보여줘야 할 때가 있다.

그럴 때 리스트 항목에 어떻게 뷰를 추가하는지 샘플이다.

 

결과이미지

 


가변뷰 layout

리스트에 추가적으로 붙일 layout

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_child"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_bg_cell_click"
    android:padding="5dp"
    android:text="Child"
    android:textColor="@android:color/white"
    android:textSize="12sp" />

 


 

리스트에서 가변뷰를 붙이기 위한 부모뷰 설정

다른 부분은 이전 것과 동일하고 마지막에 LinearLayout ll_base 부모뷰를 추가했다.

<?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="wrap_content"
    android:padding="8dp"
    android:background="@drawable/common_btn_cell"
    android:id="@+id/cl_base">

    <TextView
        android:id="@+id/textViewCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="코드:"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewProductCode"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textViewCode"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="P001" />

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="이름:"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewCode" />

    <TextView
        android:id="@+id/textViewProductName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textViewName"
        app:layout_constraintTop_toBottomOf="@+id/textViewProductCode"
        tools:text="샘플 상품명" />

    <LinearLayout
        android:id="@+id/ll_base"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="@+id/textViewProductName"
        app:layout_constraintStart_toStartOf="@+id/textViewName"
        app:layout_constraintTop_toBottomOf="@+id/textViewName"
        app:layout_constraintBottom_toBottomOf="parent">

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 


 

Adapter에서 처리방법

지금은 샘플이여서 리스트의 순서에 따라 Child뷰를 추가하는 방식으로 처리했다.

뷰를 추가하는 부분은 onBindViewHolder에서 처리하며

재사용되면서 메모리 문제가 생길 수 있어서 반드시 removeAllViews()를 통해

추가적으로 붙였던 가변뷰들을 제거해 주어야 한다.

class AdapterRecyclerView (private val _listInfoProduct: List<InfoProduct>, val _onClickListener:OnClickListener) :
    RecyclerView.Adapter<AdapterRecyclerView.AdapterRecyclerViewHolder>() {

    // 데이터 리스트의 아이템 개수를 반환
    override fun getItemCount(): Int { return _listInfoProduct.size }

    // 새로운 뷰 홀더 객체를 생성
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterRecyclerViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cell_product, parent, false)
        return AdapterRecyclerViewHolder(view)
    }

    // 뷰 홀더 클래스: 아이템 레이아웃 내의 뷰를 관리
    class AdapterRecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val _clBase:ConstraintLayout = itemView.findViewById(R.id.cl_base)
        val _productCode: TextView = itemView.findViewById(R.id.textViewProductCode)
        val _productName: TextView = itemView.findViewById(R.id.textViewProductName)
        val _llBase:LinearLayout = itemView.findViewById(R.id.ll_base)
    }

    // 뷰 홀더에 데이터를 바인딩
    override fun onBindViewHolder(holder: AdapterRecyclerViewHolder, position: Int) {
        val currentProduct = _listInfoProduct[position]
        holder._productCode.text = currentProduct._strCode
        holder._productName.text = currentProduct._strName
        holder._clBase.setOnClickListener(_onClickListener)
        holder._clBase.setTag(_listInfoProduct.get(position))
        // 높이변경
        //var layoutParams = holder.itemView.layoutParams
        //layoutParams.height = 300
        //holder.itemView.layoutParams = layoutParams

        // 재사용시 기존뷰를 모두 제거
        holder._llBase.removeAllViews()
        for(i in 0 until position){
            val tvChild:TextView = LayoutInflater.from(holder._llBase.context).inflate(R.layout.cell_child, holder._llBase, false) as TextView
            tvChild.text = "CHILD: ${i}"
            holder._llBase.addView(tvChild)
        }
    }
}

 


 

기타 레이아웃이나 디자인

레이아웃이나 디자인은 이전에 올린 RecyclerView Custom 디자인 적용과 동일하다.

https://quantum-programmer.tistory.com/entry/RecyclerView-Custom-%EB%94%94%EC%9E%90%EC%9D%B8-%EC%A0%81%EC%9A%A9

 

RecyclerView Custom 디자인 적용

RecyclerView에서 리스트의 아이템들을 버튼처럼 디자인 적용하였다.리스트의 한 개의 아이템의 layout을 구성하고기본적으로 보이는 배경디자인클릭했을 때 배경디자인이렇게만 구성한 샘플이다.

quantum-programmer.tistory.com