public OnClickListener submitOcl = new OnClickListener() {
public void onClick(View v) {
vibrator.vibrate(30);
//convert from edittext
e = editText1.getText().toString();
e2 = editText2.getText().toString();
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
// This is my problem!!!Can't set toast about empty fields
if(e.length()==0 && e2.length()==0){
toast = Toast.makeText(getApplicationContext(),
"Fill all fields", Toast.LENGTH_SHORT);
toast.show();
}
//if min more than max value output error
if(num1>num2){
toast = Toast.makeText(getApplicationContext(),
"Error", Toast.LENGTH_SHORT);
toast.show();
}
//output random int value
else if (e.length()>0 && e2.length()>0){
int range = num2 - num1 + 1;
int randomNum = r.nextInt(range) + num1;
tvResult1.setText(""+randomNum);
}
}
};
你提到:
这是我的问题!!无法设置有关空字段的吐司
if(e.length()==0 && e2.length()==0){
而是尝试使用 isEmpty()
进行检查。因此,如果您想检查它们是否都是空的,那么:
if(e.isEmpty() && e2.isEmpty()){
}
附加信息:如果要检查读取EditText
返回的字符串是否既不为空也不null
,请使用 if( e!=null && !e.isEmpty()){}
希望这有帮助。
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
如果 EditText 为空,这些行将使应用程序崩溃,因为您无法将空String
解析为integer
。
我不知道你的问题是什么,因为你没有告诉我们,但试试这个:
e = editText1.getText().toString();
e2 = editText2.getText().toString();
try {
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
}catch (Exception f) {
Toast.makeText(getApplicationContext(), "Fill all fields", 0).show();
}
// you don't need this following code because if an EditText is empty,
// it will be caught in the error and the toast above will execute
// but here is how you could also do it anyways:
/*if(e.isEmpty() && e2.isEmpty()){
toast = Toast.makeText(getApplicationContext(), "Fill all fields",
Toast.LENGTH_SHORT);
toast.show();
}*/
首先,您可以使用 TextUtils.isEmpty 来检查字符串是否为空或空。其次,您可以使用"or"运算符而不是"and"。(正如我从你的吐司消息中看到的那样。
编辑:我已经编辑了你的代码。
public OnClickListener submitOcl = new OnClickListener() {
public void onClick(View v) {
vibrator.vibrate(30);
// convert from edittext
e = editText1.getText().toString();
e2 = editText2.getText().toString();
// This is my problem!!!Can't set toast about empty fields
if (TextUtils.isEmpty(e) || TextUtils.isEmpty(e2)) {
Toast.makeText(getApplicationContext(), "Fill all fields", Toast.LENGTH_SHORT).show();
} else {
try {
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
} catch (Throwable t) {
Toast.makeText(getApplicationContext(), "Only numeric to all fields", Toast.LENGTH_SHORT).show();
return;
}
// if min more than max value output error
if (num1 > num2) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
} else {
// output random int value
int range = num2 - num1 + 1;
int randomNum = r.nextInt(range) + num1;
tvResult1.setText("" + randomNum);
}
}
}
};