我正在尝试使用 Switch 在 Android 中启用和禁用 EditText
。
如果开关为 true,我希望启用 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);
}
问题是日志只显示“DISABLED”,因为开关一开始就处于禁用状态。
最佳答案
您可以设置开关的OnCheckedChangeListener
。
switchGaranzia.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//enable
} else {
//disable
}
}
});
关于java - 使用 Android Studio 中的开关启用/禁用 editText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65222494/