Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce editText not to start with space

Tags:

android

I have a edit Text.I don't want the first letter to be space. If user hit the space as first letter cursor should not move.

like image 765
stack Learner Avatar asked Jun 22 '16 10:06

stack Learner


1 Answers

Create a TextWatcher like this

public class MyTextWatcher implements TextWatcher {
    private EditText editText;

    public MyTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = editText.getText().toString();
        if (text.startsWith(" ")) {
            editText.setText(text.trim());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}

And add this to your EditText

editText.addTextChangedListener(new MyTextWatcher(editText));
like image 128
Rehan Avatar answered Sep 17 '22 14:09

Rehan