I did what you guys were looking for. Here is my class LimitedEditText .
Features:
- you can limit the number of rows in the LimitedEditText component
- you can limit the number of characters in the LimitedEditText component
- If you exceed the limit of characters or lines somewhere in the middle of the text, the cursor will not lead you to the end - it will remain where you were.
Im disables the listener because every call to the setText() method recursively calls these three callback methods if the user has exceeded the character or string limit.
the code:
import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.widget.EditText; import android.widget.Toast; public class LimitedEditText extends EditText { private int maxLines = 1; private int maxCharacters = 50; private Context context; public int getMaxCharacters() { return maxCharacters; } public void setMaxCharacters(int maxCharacters) { this.maxCharacters = maxCharacters; } @Override public int getMaxLines() { return maxLines; } @Override public void setMaxLines(int maxLines) { this.maxLines = maxLines; } public LimitedEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; } public LimitedEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public LimitedEditText(Context context) { super(context); this.context = context; } @Override protected void onFinishInflate() { super.onFinishInflate(); TextWatcher watcher = new TextWatcher() { private String text; private int beforeCursorPosition = 0; @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
Garet May 03 '13 at 19:11 2013-05-03 19:11
source share