I have an activity in which there are three EditTexts: First Name, Middle Name, Last Name, and a Submit button. If the user submits with a field blank, a different toast appears for different field. Here's is an example when button will be clicked!:

有帮助吗?

解决方案

I'll assume you can figure out how to use a button listener yourself. Inside that button listener, you can use this code:

// create EditText references
EditText etFirstName = (EditText)findViewById(R.id.firstName);
EditText etMiddleName = (EditText)findViewById(R.id.middleName);
EditText etLastName = (EditText)findViewById(R.id.lastName);

// boolean variables that each represent whether or not the each field is blank
// if the EditText length is 0, it's true (blank); otherwise, it's false (filled)
boolean firstNameBlank = etFirstName.length() == 0;
boolean middleNameBlank = etMiddleName.length() == 0;
boolean lastNameBlank = etLastName.length() == 0;

if (firstNameBlank && middleNameBlank && lastNameBlank) {
    // toast all three blank  
}
else if (firstNameBlank && middleNameBlank) {
    // toast just first and middle are blank
}
else if (firstNameBlank && lastNameBlank) {
    // toast just first and last are blank
}
else if (middleNameBlank && lastNameBlank) {
    // toast just middle and last are blank
}
else if (firstNameBlank) {
    // toast just first is blank
}
else if (middleNameBlank) {
    // toast just middle is blank
}
else if (lastNameBlank) {
    // toast just last is blank
}
else {
    // none are blank
}

其他提示

Try this way

EditText e = (EditText)findViewById(R.id.EDITTEXT));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}

implement onClick() event of your submit button as below:

 @Override
public void onClick(View view) {

    super.onClick(view);


    switch (view.getId()) {
         case R.id.btnSubmit:
                if(edtFirstName.getText().toString().length() < 1){
                    Toast.makeText(this, "please fill all boxes.",Toast.LENGTH_LONG).show();
                }else if(edtSecondName.getText().toString().length() < 1){
                    Toast.makeText(this, "please fill middle name and last name.",Toast.LENGTH_LONG).show();
                } else if(edtLastName.getText().toString().length() < 1){
                    Toast.makeText(this, "please fill last name.",Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(this, "please wait...processing.",Toast.LENGTH_LONG).show();
                }
             break; 

         default:
               break;

        }

    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top