【Android】RecyclerView+RadioButton의 작성


RadioGroup을 사용하지 않고 작성합니다.

Main 레이아웃 작성



RecyclerView 배치

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"
    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/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/view_item" />

</androidx.constraintlayout.widget.ConstraintLayout>

아이템 만들기



RadioButton 배치

view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="1" />

어댑터 작성



RecyclerView 용 어댑터 작성.
어느 버튼을 선택하고 있는지를 나타내는 변수 checkPosition 를 작성해, onBindViewHolder 함수내에서 버튼 탭시에 notifyDataSetChanged() 를 호출하는 것이 포인트.

ItemAdapter.kt
class ItemAdapter(private val items: List<String>) :
    RecyclerView.Adapter<ItemAdapter.ViewHolder>() {

    private var checkPosition = -1

    class ViewHolder(val binding: ViewItemBinding) : RecyclerView.ViewHolder(binding.root)

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.button.text = items[position]
        holder.binding.button.isChecked = position == checkPosition
        holder.binding.button.setOnClickListener {
            checkPosition = position
            notifyDataSetChanged()
        }
    }

    override fun getItemCount() = items.size
}

MainActivity 만들기



방금 만든 Adapter 세트

MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        binding.recyclerView.adapter = ItemAdapter((1..20).map { it.toString() })
        setContentView(binding.root)
    }
}

좋은 웹페이지 즐겨찾기