Java 如果数字字段为空,如何禁用2个按钮
我有两个按钮和一个数字字段,如果我按下一个按钮而字段中没有任何内容,它就会崩溃,所以我要做的是禁用按钮,除非数字字段中有内容,我已经四处寻找答案,但要么它们不相关,要么我不确定它如何适合我的代码,下面是每个按钮的两个onClick函数。谢谢Java 如果数字字段为空,如何禁用2个按钮,java,android,button,Java,Android,Button,我有两个按钮和一个数字字段,如果我按下一个按钮而字段中没有任何内容,它就会崩溃,所以我要做的是禁用按钮,除非数字字段中有内容,我已经四处寻找答案,但要么它们不相关,要么我不确定它如何适合我的代码,下面是每个按钮的两个onClick函数。谢谢 public void toPounds(View view){ EditText amount = (EditText)findViewById(R.id.amount); Double omrAmount = Double.parseD
public void toPounds(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double omrAmount = Double.parseDouble(amount.getText().toString());
Double gbrAmount = omrAmount * 1.79;
Toast.makeText(getApplicationContext(), "£" + gbrAmount.toString(), Toast.LENGTH_LONG).show();
}
public void toRiyals(View view){
EditText amount = (EditText)findViewById(R.id.amount);
Double gbrAmount = Double.parseDouble(amount.getText().toString());
Double omrAmount = gbrAmount / 1.79;
Toast.makeText(getApplicationContext(), omrAmount.toString() + " Riyals", Toast.LENGTH_LONG).show();
}
如果要在编辑文本为空时禁用按钮,则可以执行以下操作:
EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
button.setEnabled(false);
}
amount.addTextChangedListener(新的TextWatcher(){
这并不是对你问题的具体回答,但一般来说,在调用导致应用程序崩溃的代码之前,你希望添加某种检查。让导致应用程序崩溃的代码继续存在不是一个好主意
可能会创建一个类似于:isMyEditTextValid(…){..}的方法,在按钮上按第一次检查数字字段是否为空
EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
button.setEnabled(false);
}
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() == 0)
button1.setEnabled(false)
else
button1.setEnabled(true)
}
});