I want to display multiple radio buttons in a layout with multiline style as an item inside a RecyclerView
. Look at the code I provided below and suggest how I can refactor the code to be more efficient or optimized:
Layout in XML:
<RadioButton
android:id="@+id/rb_rad1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_10"
android:checked="true"
android:text="@string/text1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/xyz" />
<RadioButton
android:id="@+id/rb_rad2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dp_34"
android:checked="false"
android:text="@string/text2"
app:layout_constraintBaseline_toBaselineOf="@+id/rb_rad1"
app:layout_constraintLeft_toRightOf="@+id/rb_rad1" />
<RadioButton
android:id="@+id/rb_rad3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="@string/text3"
app:layout_constraintLeft_toLeftOf="@+id/rb_rad1"
app:layout_constraintTop_toBottomOf="@+id/rb_rad1" />
<RadioButton
android:id="@+id/rb_rad4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="@string/text4"
app:layout_constraintLeft_toLeftOf="@+id/rb_rad2"
app:layout_constraintTop_toBottomOf="@+id/rb_rad2" />
Inside the onBindViewHolder()
method:
holder.binding.rbRad1.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad3.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad3.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad2.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad3.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad4.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad3.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})