[英]How can I check if edittext is empty?
我有兩個編輯文本和一個計算按鈕。 我將輸入兩個數字,當我點擊計算按鈕時,我想對這兩個數字求和。然后,當我點擊按鈕時,我想通過捆綁在另一個活動中顯示這個結果。 但是,如果這些編輯文本為空,則會出現諸如此應用程序停止之類的錯誤。 我該如何解決這些問題? 謝謝 ...
float number1,number2;
float resultNet;
Bundle bundle = new Bundle();
number1 = Float.parseFloat(edittext1.getText().toString());
number2 = Float.parseFloat(edittext2.getText().toString());
if((!"".equals(edittext1)) && (!"".equals(edittext2)))
{
// result = number1 - number2/4;
//bundle.putFloat("resultNet",resultnet);
Intent intent = new Intent(Calculations.this,CalculationsResults.class);
intent.putExtras(bundle);
startActivity(intent);
}
else
{
resultNet = number1 - number2/4;
bundle.putFloat("resultNet",resultnet);
Intent intent = new Intent(Calculations.this,CalculationsResults.class);
intent.putExtras(bundle);
startActivity(intent);
}
resultCalculation = findViewById(R.id.result);
Bundle bundle = getIntent().getExtras();
float resultNet = bundle.getFloat("resultNet");
if(bundle!= null)
{
resultCalculation.setText("Sum Result:"+ resultNet);
}
您應該檢查 EditText 中文本的值,然后在您知道它們合適時使用這些值:
// Get the value of the text within the EditText
String enteredText1 = myEditText1.getText().toString();
String enteredText2 = myEditText2.getText().toString();
// Use String comparison to check if the text isn't empty
if(!enteredText1.equals("") && !enteredText2.equals(""){
// Now you know the values aren't empty
float myVal = Float.parseFloat(enteredText1);
float myVal2 = Float.parseFloat(enteredText2);
// do something with the values ...
}else{
// do something when the values are empty ...
}
EditText textA = (EditText) findViewById(R.id.text1);
EditText textB = (EditText) findViewById(R.id.text2);
String fieldText1 = textA.getText().toString();
String fieldText2 = textB.getText().toString();
if (fieldText1.matches("") || fieldText2.matches("")) {
Toast.makeText(this, "Please, Fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.