似乎您需要将TextChangedListener添加到您的编辑和准备处理中。
这是在开头插入+7的小例子(实际上,对于 - 中间逻辑保持不变,只需要另一个字符串操作):
/** Helper to control input phone number */
static class PrefixEntryWatcher implements TextWatcher {
/** flag to avoid re-enter in {@link PhoneEntryWatcher#afterTextChanged(Editable)}*/
private boolean isInAfterTextChanged = false;
/** Prefix to insert */
private final String prefix;
/** Prefix to insert length */
private final int prefixLength;
/** Weak reference to parent text edit */
private final WeakReference parentEdit;
/**
* Default constructor
*
* @param prefix to be used for prefix
*/
PrefixEntryWatcher(final String prefix, final EditText parentEdit) {
this.prefix = prefix;
this.prefixLength = (prefix == null ? 0 : prefix.length());
this.parentEdit = new WeakReference(parentEdit);
}
@Override
public synchronized void afterTextChanged(final Editable text) {
if (!this.isInAfterTextChanged) {
this.isInAfterTextChanged = true;
if (text.length() <= this.prefixLength) {
text.clear();
text.insert(0, this.prefix);
final EditText parent = this.parentEdit.get();
if (null != parent) {
parent.setSelection(this.prefixLength);
}
}
else {
if (!this.prefix.equals(text
.subSequence(0, this.prefixLength).toString())) {
text.clear();
text.insert(0, this.prefix);
}
final String withoutSpaces
= text.toString().replaceAll(" ", "");
text.clear();
text.insert(0, withoutSpaces);
}
// now delete all spaces
this.isInAfterTextChanged = false;
}
}
@Override
public void beforeTextChanged(final CharSequence s,
final int start,
final int count,
final int after) {
// nothing to do here
}
@Override
public void onTextChanged(final CharSequence s,
final int start,
final int before,
final int count) {
// nothing to do here
}
}它的代码和逻辑并不多,因此这种类型的EditText处理似乎不需要第三方库。