我有2个字段和一个按钮。我想在字段为空时禁用该按钮。我尝试了很多解决方案,但仍然无效。这是我的代码:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnCount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String p1 =
edtP.getText().toString().trim();
String l2 =
edtL.getText().toString().trim();
double dp = Double.parseDouble(p1);
double dl = Double.parseDouble(l2);
double total = dp * dl;
txtT.setText("equals: " +total);
if ( ( !p1.trim().isEmpty()) && ( !l2.trim().isEmpty()) ) {
btnCount.setEnabled(false);
}
}
}); }
每次运行项目时,我总是会收到此错误:
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
答案 0 :(得分:1)
将textChange侦听器添加到两个字段和两个字段的onTextChanged方法中,检查提供的文本是否为空。如果为空则禁用按钮,否则启用按钮。
Field1.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 && Field2.getText().toString.length()!=0){
// enable the button
}else{
// disable the button
}
}
});
Field2.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 && Field1.getText().toString.length()!=0){
// enable the button
}else{
// disable the button
}
}
});
答案 1 :(得分:1)
试试这个:
btnCount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(edtP.getText().toString().length()>0 && edtL.getText().toString().length()>0){
String p1 =
edtP.getText().toString().trim();
String l2 =
edtL.getText().toString().trim();
double dp = Double.parseDouble(p1);
double dl = Double.parseDouble(l2);
double total = dp * dl;
txtT.setText("equals: " +total);
if ( !(p1.trim().isEmpty()) && ( !l2.trim().isEmpty()) ) {
btnCount.setEnabled(true);
}
else{
btnCount.setEnabled(false);
}
}
else{
Toast.makeText(getApplicationContext(),"Edittexts are empty",Toast.LENGTH_LONG).show();
}
}
}); }
答案 2 :(得分:-1)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnCount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String p1 = edtP.getText().toString().trim();
String l2 = edtL.getText().toString().trim();
double dp = 0, dl = 0, total = 0;
try{
dp = Double.parseDouble(p1);
dl = Double.parseDouble(l2);
total = dp * dl;
txtT.setText("equals: " +total);
}catch(Exception e){
dp = -1;
dl = -1;
btnCount.setEnabled(false);
}
}
});
}