본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 리사이클러뷰 안에 뷰페이저 넣기

by teamnova 2022. 3. 7.

안녕하세요 이번 포스팅에선 리사이클러뷰 안에 뷰페이저를 넣어보겠습니다.

사용할 뷰페이저는 viewPager2로 리사이클러뷰를 상속받고 있기 때문에 리사이클러뷰처럼 사용하면 됩니다.

코드상의 차이점은, 리사이클러뷰는 레이아웃 매니저와 어댑터를 설정해주어야 하지만, 뷰페이저는 레이아웃 매니저 없이 어댑터만 설정해주면 된다는 것입니다.

 

코드는 sdk 28인 상태에서 테스트되고 뷰바인딩이 사용됩니다.

 

 

Palette.kt

리사이클러뷰에 표시될 아이템 클래스

data class Palette(
    val name: String,
    val colors: ArrayList<String>
)

item_palette.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="200dp"
    android:layout_margin="10dp"
    android:background="@color/teal_700"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_palette"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginVertical="10dp"
        android:gravity="center_horizontal"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

PaletteAdapter.kt

리사이클러뷰 어댑터

class PaletteAdapter : RecyclerView.Adapter<PaletteAdapter.ViewHolder>() {

    lateinit var items: ArrayList<Palette>

    fun build(i: ArrayList<Palette>): PaletteAdapter {
        items = i
        return this
    }

    class ViewHolder(val binding: ItemPaletteBinding, val context: Context) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Palette) {
            with(binding)
            {
                tvPalette.text = item.name
                viewPager.adapter = ColorAdapter().build(item.colors)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaletteAdapter.ViewHolder =
        ViewHolder(
            ItemPaletteBinding.inflate(LayoutInflater.from(parent.context), parent, false),
            parent.context
        )

    override fun onBindViewHolder(holder: PaletteAdapter.ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int = items.size
}

 

item_color.xml

뷰페이저 아이템 레이아웃

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_color"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:background="@color/black"
    android:gravity="center"
    android:textColor="@color/purple_500"
    android:textSize="50sp" />

ColorAdapter.kt

뷰페이저의 어댑터

class ColorAdapter : RecyclerView.Adapter<ColorAdapter.ViewHolder>() {

    lateinit var items: ArrayList<String>

    fun build(i: ArrayList<String>): ColorAdapter {
        items = i
        return this
    }

    class ViewHolder(val binding: ItemColorBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: String) {
            binding.tvColor.text = item
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorAdapter.ViewHolder =
        ViewHolder(ItemColorBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: ColorAdapter.ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int = items.size
}

activity_palette.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=".PaletteActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_palette"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

PaletteActivity.kt

액티비티 클래스

class PaletteActivity : AppCompatActivity() {

    lateinit var binding: ActivityPaletteBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityPaletteBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.rvPalette.apply {
            adapter = PaletteAdapter().build(palettes)
            layoutManager =
                LinearLayoutManager(this@PaletteActivity, LinearLayoutManager.VERTICAL, false)
        }
    }

    val palettes = arrayListOf<Palette>(
        Palette("cozy", arrayListOf("pink", "purple", "sky blue", "white")),
        Palette(
            "rainbow",
            arrayListOf("red", "orange", "yellow", "green", "blue", "indigo", "purple")
        ),
        Palette(
            "Healthy Leaves",
            arrayListOf("Olive Green", "Lime Green", "Yellow Green", "Green")
        ),
        Palette("korea", arrayListOf("white", "black", "blue", "red")),
        Palette("usa", arrayListOf("blue", "red", "white")),
        Palette("italy", arrayListOf("green", "white", "red")),
        Palette("china", arrayListOf("red", "yellow")),
        Palette("google", arrayListOf("red", "yellow", "green", "blue")),
    )
}