Android A method of limiting the number of words to be entered
- 2021-01-14 06:33:15
- OfStack
This article shows an example of how Android can limit the number of words entered. To share with you for your reference, as follows:
// Sina weibo word limit
private static final int WEIBO_CONTENT_LENGTH_LIMITED = 140;
// Add Twitter content edittext
mInputEditText.addTextChangedListener(mTextWatcher);
private TextWatcher mTextWatcher = new TextWatcher() {
private int editStart;
private int editEnd;
public void afterTextChanged(Editable s) {
editStart = mInputEditText.getSelectionStart();
editEnd = mInputEditText.getSelectionEnd();
// Remove the listener first, otherwise there will be a stack overflow
mInputEditText.removeTextChangedListener(mTextWatcher);
while (mInputEditText.getText().toString().length() > WEIBO_CONTENT_LENGTH_LIMITED) {
s.delete(editStart - 1, editEnd);
editStart--;
editEnd--;
}
mInputEditText.setText(s);
mInputEditText.setSelection(editStart);
mInputEditText.addTextChangedListener(mTextWatcher);
setPromptContent();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
/**
* refresh prompt content numbers
*/
private void setPromptContent() {
int contentLength = mInputEditText.getText().toString().length();
mInputEditText.setSelection(contentLength);
int limitedLength = WEIBO_CONTENT_LENGTH_LIMITED - contentLength;
String prefix = getResources().getString(R.string.weibo_content_numbers_prefix);
String suffix = getResources().getString(R.string.weibo_content_numbers_suffix);
String promptContentNumbers = prefix + limitedLength + suffix;
SpannableStringBuilder style = new SpannableStringBuilder(promptContentNumbers);
style.setSpan(new ForegroundColorSpan(Color.RED), prefix.length(), promptContentNumbers.length() - suffix.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPromptContentNumbers.setText(style);
}
More about Android controls related content interested readers can view the site: Android controls usage summary
I hope this article is helpful to Android program design.