用户开始键入后如何在EditText中添加字符 [英] How to add a character in EditText after user starts typing
本文介绍了用户开始键入后如何在EditText中添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个editText,用户在其中输入电话号码,但是当他们单击其第一个数字时,我希望在文本的开头出现一个"+".我有此代码,但"+"一直存在.我只希望它在用户输入数字时显示,我该如何解决?
I have an editText where a user inputs a phone number, but right when they click their first number, I want a '+' to appear in the beginning of the text. I have this code but the '+' is constantly there. I only want it to appear when a user inputs a number, how would I fix this?
final EditText editText = findViewById(R.id.register_edit_phone);
final String prefix = "+";
editText.setText(prefix);
Selection.setSelection(editText.getText(), editText.getText().length());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().startsWith(prefix)) {
editText.setText(prefix);
Selection.setSelection(editText.getText(), editText.getText().length());
}
}
});
推荐答案
Pattern p = Pattern.compile("^\\d+.*");
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (p.matcher(s.toString().trim()).matches()) {
editText.setText(prefix + s.toString());
}
Selection.setSelection(editText.getText(), editText.getText().length());
}
});
这篇关于用户开始键入后如何在EditText中添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文