Reputation: 1348
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.
Upvotes: 8
Views: 6713
Reputation: 2354
You can set InputFilter
to your Edittext
by following method. It will restrict user to enter space in starting.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length()>0 &&Character.isWhitespace(source.charAt(0)) && yourEditText.getText().toString().length()==0) {
return "";
}
return source;
}
};
yourEditText.setFilters(new InputFilter[] { filter });
InputFilter
is more reliable in terms of performance as compared toTextWatcher
in this scenario. You can refer https://stackoverflow.com/a/33855940/3817374 for more detailed informarion.
Upvotes: 1
Reputation: 3285
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));
Upvotes: 10
Reputation: 385
Basing on the first answer by Luca:
TextWatcher mWatcher = new TextWatcher() {
@Override public void afterTextChanged(Editable editable) {
if (myEditText.getText().toString().startsWith(" "))
myEditText.setText("");
}
Here I changed equals
to startsWith
Than set it
Upvotes: 4
Reputation: 17
Add an if else condition to check the first letter
if(EditText.getText().charAt(0)!=" "){
//COOL!
}
else
{
//ERROR!
}
Make sure that it is run on the ui thread
Upvotes: -1
Reputation: 2397
TextWatcher myWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (myEditText.getText().toString().equals(" "))
myEditText.setText("");
}
and then
myEditText.addTextChangedListener(myWatcher);
Upvotes: 1