How to make a Toast to pop up when the user tries to insert text longer than maximum limit?
<EditText
android:maxLength="28"
...
/>
I tried to use TextWatcher but it doesn’t work properly:
public class MyActivity extends Activity implements TextWatcher
{
// ...
@Override
public void afterTextChanged(Editable arg0){}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3){}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
if(etUsername.isFocused() && etUsername.getText().length() == 28)
Toast.makeText(MyActivity.this, "The username must be at most 28 characters!" , Toast.LENGTH_SHORT).show();
else if(etPassword.isFocused() && etPassword.getText().length() == 10)
Toast.makeText(MyActivity.this, "The password must be at most 10 characters!" , Toast.LENGTH_SHORT).show();
}
}
EDIT:
I also tried to put the code inside afterTextChanged and beforeTextChanged but it doesn’t solve the problem.
EDIT2:
What I want is that the Toast only can be popped up when there are 28 characters in the EditText and the user is trying to add a 29th character. The Toast in my code above will pop up only if there are 27 characters in the TextEdit and the user inserts a 28th character.
The only way to achieve desired functionality is to change
android:maxLengthtodesiredMaxLength + 1and to check for the length inafterTextChanged(). You will have to manually delete the last character when length == desiredMaxLength + 1 (i.e. manipulate thesparameter inafterTextChanged(Editable s)). Please be careful not to put yourself in infinite loop because after changingsafterTextChanged()will be called again.