[英]Enable/Disable editText with a Switch in Android Studio
I'm trying to enable and disable an EditText
in Android, using a Switch.我正在尝试使用 Switch 在 Android 中启用和禁用EditText
。
If the switch is true, I want that the EditText is enabled and I can write in it.如果开关为真,我希望启用 EditText 并且我可以在其中写入。 If the switch is false, I want that the EditText is disabled and I can't write in it.如果开关为假,我希望 EditText 被禁用并且我不能在其中写入。
I've tried like this but it doesn't work.我试过这样,但它不起作用。
Here is the XML:这是 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:这是 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);
}
The problem is that the log show me only "DISABLED", because the switch starts off disabled.问题是日志只显示“禁用”,因为开关开始时是禁用的。
You can set the OnCheckedChangeListener
of the switch.您可以设置开关的OnCheckedChangeListener
。
switchGaranzia.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//enable
} else {
//disable
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.