【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" />

Adapter作成

RecyclerView用のAdapter作成。
どのボタンを選択しているかを表す変数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)
    }
}