Reputation: 75
when i skip the EditText field(eg:name),i want to display error message like "name field is empty". this is my code,
public void onClick(View v) {
String userName=username.getText().toString();
String passWord=password.getText().toString();
if (userName.equals("")){
username.setError("Username Required");
}
else if(passWord.isEmpty()){
password.setError("Password Required");
}
else{
Toast.makeText(Login.this, "Success", Toast.LENGTH_SHORT).show();
}
}
please help me.
Upvotes: 1
Views: 123
Reputation: 910
Suppose you are trying to check valid username then on text change event of EditText you can use this code.
edit_name.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
@Override
public void afterTextChanged(Editable s) {
Is_Valid_Person_Name(edit_name);
}
});
It is pretty simple and will show you error in red color exactly beside to the editText which you are filling as you can see on this site
public void Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Accept Alphabets Only.");
name = null;
} else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
edt.setError("Accept Alphabets Only.");
name = null;
} else {
name = edt.getText().toString();
edt.setError(null);
}
}
Similar way you can apply other validations..
Upvotes: 0
Reputation: 4335
Try this, using setOnFocusChangeListener()
UserName.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
String userName=username.getText().toString();
if (userName.equals("")){
username.setError("name field is empty");
username.requestFocus();
}
}
}
});
Password.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
String passWord=password.getText().toString();
if(passWord.equals("")){
password.setError("Password Required");
password.requestFocus();
}
}
}
});
Upvotes: 0
Reputation: 362
on button click you can check edit text empty or nor then show error
public void onClick(View v) {
String userName=username.getText().toString();
String passWord=password.getText().toString();
if (userName.equals("")){
username.setError("name field is empty");
}
else if(passWord.isEmpty()){
password.setError("Password Required");
}
else{
Toast.makeText(Login.this, "Success", Toast.LENGTH_SHORT).show();
}
}
Upvotes: 1