Java 如果选中复选框,则不必验证editext;如果未选中editext,则必须验证
我在验证链接在一起的复选框和EditText时遇到问题,如果选中复选框,EditText字段可以为空,如果未选中,EditText字段不能为空,因为您没有提供任何代码,我编写了一些代码片段来帮助解释如何实现这一点 XML 希望你能从这里开始。如您所见,复选框和编辑文本有4种不同的情况Java 如果选中复选框,则不必验证editext;如果未选中editext,则必须验证,java,Java,我在验证链接在一起的复选框和EditText时遇到问题,如果选中复选框,EditText字段可以为空,如果未选中,EditText字段不能为空,因为您没有提供任何代码,我编写了一些代码片段来帮助解释如何实现这一点 XML 希望你能从这里开始。如您所见,复选框和编辑文本有4种不同的情况 请记住,在我的代码中,if语句是在单击按钮时发生的,但是您可能希望进行不同的检查。无论如何,如何处理每种不同的情况取决于您。请发布您迄今为止编写的代码,并指出其中哪一部分没有按照您的预期工作。 <Chec
请记住,在我的代码中,if语句是在单击按钮时发生的,但是您可能希望进行不同的检查。无论如何,如何处理每种不同的情况取决于您。请发布您迄今为止编写的代码,并指出其中哪一部分没有按照您的预期工作。
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox"
android:layout_gravity="center_horizontal"
android:text="Check me!"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/edittext"
android:layout_gravity="center_horizontal"
android:hint="Edit me!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:text="Click me!"/>
final CheckBox cb = (CheckBox) findViewById(R.id.checkbox);
final EditText et = (EditText) findViewById(R.id.edittext);
final Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if(cb.isChecked()){
if(et.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Checkbox checked and EditText empty", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Checkbox checked and EditText not empty", Toast.LENGTH_SHORT).show();
}
}else{
if(et.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Checkbox not checked and EditText empty", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Checkbox not checked and EditText not empty", Toast.LENGTH_SHORT).show();
}
}
}
});