public void add(View v)
{
EditText first=findViewById(R.id.first),second=findViewById(R.id.second);
double f=Double.parseDouble(first.getText().toString());
double s=Double.parseDouble(second.getText().toString());
TextView result=findViewById(R.id.result);
double r;
if(TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if(TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
r = f + s;
result.setText("" + r);
}
}
如果editText为空,我想从用户输入两个数字并显示错误信息 但是在执行这段代码时,我的应用程序一直在崩溃。
答案 0 :(得分:3)
如果Editext
值不为空,则需要将Double
值转换为Editext
试试这个
public void add(View v)
{
EditText first=findViewById(R.id.first);
EditText second=findViewById(R.id.second);
TextView result=findViewById(R.id.result);
double r;
if(TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if(TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
double s=Double.parseDouble(second.getText().toString());
double f=Double.parseDouble(first.getText().toString());
r = f + s;
result.setText("" + r);
}
}
答案 1 :(得分:3)
全球宣布第二名
public void add(View v) {
first = findViewById(R.id.first);
second = findViewById(R.id.second);
TextView result = findViewById(R.id.result);
double r;
if (Validates()) {
double s = Double.parseDouble(second.getText().toString());
double f = Double.parseDouble(first.getText().toString());
r = f + s;
result.setText("" + r);
}
}
public boolean Validates() {
if (first.getText().toString().equalsIgnoreCase("")) {
first.setError("This field can't be empty");
return false;
} else if (second.getText().toString().equalsIgnoreCase("")) {
second.setError("This field can't be empty");
return false;
} else {
return true;
}
}
答案 2 :(得分:1)
例如:
if((first.gettext().toString) == null ||
TextUtils.isEmpty(first.getText().toString()))
{
first.setError("This field can't be empty");
}
else if((second.gettext().toString) == null || TextUtils.isEmpty(second.getText().toString()))
{
second.setError("This field can't be empty");
}
else {
r = f + s;
result.setText("" + r);
}