Search code examples
androidkotlintogglebuttonchecked

Try to click a togglebutton and make the other togglebutton unchecked. Android Studio-Kotlin


So, hello guys,in android-studio, I've got a horizontal-linear-layout and also got two buttons in it side by side which are togglebuttons, lets call them X and Y, what I'm trying to do is, once I click X, X becomes checked then when I try to click Y, Y becomes checked but X becomes unchecked back, so how would I do it? I try to do this but eventually not worked.

    if (beginnerButton.isChecked) {
        balleButton.isChecked = false
    }
    else if (balleButton.isChecked) {
        beginnerButton. = false
    }

Solution

  • define OnClick in XML like below

    <ToggleButton
            android:id="@+id/beginnerButton"
            android:layout_width="wrap_content"
            android:onClick="clickBeginnerButton"
            android:layout_height="wrap_content"
            />
    
        <ToggleButton
            android:id="@+id/balleButton"
            android:onClick="clickBalleButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    

    and in kotlin:

      public fun clickBeginnerButton(view: View) {
        balleButton.isChecked = false
      }
    
      public fun clickBalleButton(view: View) {
        beginnerButton.isChecked = false
      }
    

    Its will working as your expected

    Hope this helps