Since setting EditText.setMaxlength or through the filters doesn't do anything on restricting the user from entering text to a specific length, I thought I will extend the EditText and handle myself but I am running into a Indexoutofbound exception.
Here is my code and I appreciate if anyone could point me to the right direction:
import android.content.Context;
import android.text.Editable;
import android.util.AttributeSet;
import android.widget.EditText;
public class EditTextExtended extends EditText
{
protected int maxTextLength = Integer.MAX_VALUE;
protected int minTextLength = Integer.MIN_VALUE;
private Boolean isTextChanged;
public EditTextExtended(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
}
public void setMaximumTextLength(int value)
{
maxTextLength = value;
}
public void setMinimumTextLength(int value)
{
minTextLength = value;
}
@Override
protected void onTextChanged(CharSequence charSequence, int start, int before, int after)
{
Editable userEnteredText = this.getText();
if (this.getText().length() > maxTextLength)
{
String maximumAllowedCharacters = userEnteredText.toString().substring(0, maxTextLength);
if (!isTextChanged)
{
isTextChanged = true;
this.setText(maximumAllowedCharacters);
}
}
super.onTextChanged(charSequence, start, before, after);
}
}
I have set the setMaximumTextLength to 10. So, when I type in 11th character it throws InvocationTrargetException with the IndexOutOfBoundsException as you see below:
So, please give me some kind of clue on what the heck am I doing wrong. By the way, am on Android 5.0.1 build target API 21.