Enable/Disable editText with a Switch in Android Studio

Viewed 550

I'm trying to enable and disable an EditText in Android, using a Switch.

If the switch is true, I want that the EditText is enabled and I can write in it. If the switch is false, I want that the EditText is disabled and I can't write in it.

I've tried like this but it doesn't work.

Here is the 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">

    <Switch
        android:id="@+id/switchGaranzia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Garanzia"
        app:layout_constraintBottom_toTopOf="@+id/numeroArticoliText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/descizioneArticoloText"
        app:layout_constraintVertical_bias="0.298" />

    <EditText
        android:id="@+id/testEnabeld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Prova"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switchGaranzia"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

And here is the Java code:

private KeyListener listener;
    private EditText textEdit;

switchGaranzia = (Switch) view.findViewById(R.id.switchGaranzia);
textEdit = (EditText) view.findViewById(R.id.testEnabeld);
        listener = textEdit.getKeyListener();

        if(switchGaranzia.isChecked()){
            Log.v("ERROR" , "ENABLED");
            textEdit.setKeyListener(null);
        } else {
            Log.v("ERROR", "DISABLED");
            textEdit.setKeyListener(listener);
        }

The problem is that the log show me only "DISABLED", because the switch starts off disabled.

1 Answers

You can set the OnCheckedChangeListener of the switch.

switchGaranzia.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            //enable
        } else {
           //disable
        }
    }
});
Related