Problems using the EditText.setError () method

3

When you try to use the EditText.setError() method, the error message does not appear. The code below is used for performing the validation of the required fields:

public class LoginActivity extends Activity {

    private EditText usuario;
    private EditText senha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        usuario = (EditText) findViewById(R.id.usuario);
        senha = (EditText) findViewById(R.id.senha);

    }

    private boolean loginValido() {

        EditText campoComFoco = null;

        boolean isValid = true;

        if (usuario.getText().toString().length() == 0) {
            campoComFoco = usuario;
            usuario.setError("Usuário obrigatório");
            isValid = false;
        }
        if (senha.getText().toString().length() == 0) {
            if (campoComFoco == null) {
                campoComFoco = senha;
            }
            senha.setError("Senha obrigatória");
            isValid = false;
        }

        if (campoComFoco != null) {
            campoComFoco.requestFocus();
        }

        return isValid;
    }

}

    
asked by anonymous 11.08.2015 / 15:00

2 answers

1

I changed my answer, depending on your edit

 final EditText txtNome = (EditText) findViewById(R.id.txtHint);

        txtNome.setOnEditorActionListener(new EditText.OnEditorActionListener()
        {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
            {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
                {
                    String campoPesquisa = txtNome.getText().toString();

                    if (TextUtils.isEmpty(campoPesquisa))
                    {
                        editText.setError("Informe o usuario");
                        vibrar(200);
                        return false;
                    }
                    }
                }

                return false; 
            }
        });

I recommend using TextUtils in this case if you want to validate if the field is empty.

onEditorAction : allows you to define what the final action of the user will be, in the example that I removed from an application of mine it triggers when the user clicks search and when you click Ok or done. >     

11.08.2015 / 15:05
0

Your code is correct, you just need to add a " focus " to the EditText that is trying to assign setError() .

Try something similar:

if (usuario.getText().toString().length() == 0) {
    campoComFoco = usuario;
    //Adicionando o foco no seu EditText
    usuario.requestFocus();
    usuario.setError("Usuário obrigatório");
    isValid = false;
}
    
11.08.2015 / 20:49