问题
My question is that How to limit specific character in edit text?
for example I want to limit # character using max. 3 times in edit text.
How can I do this? Any advice or code sample please.
thanks.
回答1:
use this
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(count>3){
yourEditText.setEnabled(false);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
回答2:
Try this
int currHash=0;
edtText.addTextChangedListener(new TextWatcher() {
CharSequence previous;
public void afterTextChanged(Editable source) {
if(source.toString().contains("#") && currHash=2){
source.clear();
source.append(previous.toString());
}
else
if(source.toString().contains("#"))
currHash++;
}
public void beforeTextChanged(CharSequence source, int start, int count, int after) {
previous = source;
}
public void onTextChanged(CharSequence source, int start, int before, int count) {}
});
回答3:
I found a solution like this.
etDesc.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
hastagCount = s.toString().length() - s.toString().replace("#", "").length();
if(hastagCount<=3){
previousDesc = s.toString();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
hastagCount = s.toString().length() - s.toString().replace("#", "").length();
if(hastagCount>3){
s.clear();
s.append(previousDesc);
int pos = etDesc.getText().length();
etDesc.setSelection(pos);
etDesc.setFocusable(true);
}
}
});
来源:https://stackoverflow.com/questions/61031014/how-to-limit-specific-character-in-edit-text