我一直在努力寻找简单的解决方案,将电话号码格式化为用户类型。 我不想使用任何库进行格式化。关于如何做的任何想法?
答案 0 :(得分:4)
似乎您需要将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<EditText> 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<EditText>(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处理似乎不需要第三方库。