How can I uncheck or reset the radio button in android/kotlin ?

I recently had the need to have a radio group where the selected item could be deselected by tapping it again. So, here I can be able to deselect all options inside anRadioGroup. I tried using click listeners but I couldn't accomplish. Then I am able to do it using a custom AppCompatRadioButton class in Kotlin as shown below: 
package com.myapp

import android.content.Context
import android.util.AttributeSet
import android.widget.RadioGroup
import androidx.appcompat.widget.AppCompatRadioButton

/**
* Created this class for custom radio button which toggles on click
*/
class ToggleAbleRadioButton(context: Context?, attrs: AttributeSet?) :
AppCompatRadioButton(context, attrs) {

override fun toggle() {
if (isChecked) {
if (parent is RadioGroup) {
(parent as RadioGroup).clearCheck()
}
} else {
isChecked = true
}
}
}

 You can use it inside radio group as shown below:

<RadioGroup
android:id="@+id/radip_group_whether_conditions"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="@id/guidelinesend"
app:layout_constraintStart_toStartOf="@id/guidelinestart"
app:layout_constraintTop_toBottomOf="@id/til_wind_direction_and_speed">

<com.myoctans.app.daily_reports.view.ToggleAbleRadioButton
android:id="@+id/mcb_sunny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sunny" />

<com.myoctans.app.daily_reports.view.ToggleAbleRadioButton
android:id="@+id/mcb_cloudy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cloudy" />

<com.myoctans.app.daily_reports.view.ToggleAbleRadioButton
android:id="@+id/mcb_rain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rain" />

<com.myoctans.app.daily_reports.view.ToggleAbleRadioButton
android:id="@+id/mcb_snow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/snow" />
</RadioGroup>

You can refer this link for more insight: Android radio button uncheck,
how to uncheck radio button in android programmatically code example

No comments:

Post a Comment

Popular Posts