我有2个按钮和1个数字字段,如果我在字段中按下没有东西的按钮,它会崩溃,所以我要做的是禁用按钮,除非数字字段中有内容,我已经四处寻找答案,但要么它们不相关,要么我不确定它是如何适合我的代码的,这里是每个按钮的两个onClick函数。感谢
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();
}
答案 0 :(得分:0)
yourField.addTextChangedListener(new TextWatcher() {
@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)
}
});
答案 1 :(得分:0)
如果要在编辑文本为空时禁用按钮,则可以执行以下操作:
EditText amount = (EditText)findViewById(R.id.amount);
Button button = (Button) findViewById(R.id.button1);
if(amount.getText().toString().isEmpty()){
button.setEnabled(false);
}
amount.addTextChangedListener(new TextWatcher(){
@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)
}
});
答案 2 :(得分:0)
并非具体回答您的问题,但一般来说,您需要在调用代码之前添加某种检查,这会使您的应用程序崩溃。让代码崩溃你的应用程序并不是一个好主意。
也许制作一个方法:isMyEditTextValid(...){..}