How do you not toggle Switch when hitting enter twice on a keyboard in Android Studio

70 views Asked by At

When pressing enter twice on the editText "textbox" the first push will submit the button as usual, but the second press will toggle the switch. How do I ensure that the switch does not get toggled?

 <com.google.android.material.textfield.TextInputEditText
          android:id="@+id/textbox"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:inputType="textCapCharacters" />

      <Switch
        android:id="@+id/switch"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:checked="false"
        android:gravity="left" />

      <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="16dp" />
1

There are 1 answers

0
SlowLearnah On

You can Either Set it to not be clickable or to make sure it stays in the same isChecked status, either will work.

    switch.setOnKeyListener(object : View.OnKeyListener{
      override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.action == KeyEvent.ACTION_DOWN){
          when(keyCode){
            KeyEvent.KEYCODE_ENTER ->{
             // switch.isClickable = false
              if (!switch.isChecked){
                !switch.isChecked
              }else{
                switch.isChecked
              }

              return true
            }
          }
        }

//        switch.isClickable = true
        return false
      }
    })