【问题标题】:Enable/Disable editText with a Switch in Android Studio在 Android Studio 中使用 Switch 启用/禁用 editText
【发布时间】:2020-12-09 18:08:13
【问题描述】:

我正在尝试使用 Switch 在 Android 中启用和禁用 EditText

如果开关为真,我希望启用 EditText 并且我可以在其中写入。 如果开关为 false,我希望 EditText 被禁用并且我不能在其中写入。

我试过这样,但它不起作用。

这是 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>

这里是 Java 代码:

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);
        }

问题是日志只显示“禁用”,因为开关开始时禁用。

【问题讨论】:

    标签: java android xml android-studio


    【解决方案1】:

    您可以设置开关的OnCheckedChangeListener

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

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多