在自动的EditText格式的电话号码 [英] Automatically format phone number in EditText
问题描述
在我的应用程序,用户可以使用以下格式输入在的EditText
字段的电话号码:
In my app, the user has to enter a phone number in an EditText
field using the following format:
1(515)555-5555
1(515)555-5555
我不希望用户键入(,),或 - ,而输入号码;我想自动添加这些字符。
I don't want the user to type "(", ")", or "-" while entering the number; I want these characters to be added automatically.
例如,假设键入 1
用户 - 1应该被自动添加后括号,使1(将显示,我会。希望有类似的功能,同时删除。
For example, suppose the user typed 1
-- the parenthesis after "1" should be added automatically, so that "1(" would be displayed. And I would like to have similar functionality while deleting.
我已经尝试设置 onTextWatcher
接口 afterTextChanged
法文本,但它不工作;相反,它是造成错误。任何帮助将大大AP preciated。
I have tried to set text in the afterTextChanged
method of onTextWatcher
interface, but it is not working; instead it's causing an error. Any help will be greatly appreciated.
推荐答案
您可能正在运行到一个问题,因为 afterTextChanged
是重入,即改变作出文本导致再次调用的方法。
You're probably running into a problem because afterTextChanged
is re-entrant, i.e. changes made to the text cause the method to be called again.
如果这就是问题所在,倒过来的一种方法是保持一个实例变量标志:
If that's the problem, one way way around is to keep an instance variable flag:
public class MyTextWatcher implements TextWatcher {
private boolean isInAfterTextChanged;
public synchronized void afterTextChanged(Editable text) {
if (!isInAfterTextChanged) {
isInAfterTextChanged = true;
// TODO format code goes here
isInAfterTextChanged = false;
}
}
}
作为替代方案,你可以只使用<一个href=\"http://developer.android.com/reference/android/telephony/PhoneNumberFormattingTextWatcher.html\">PhoneNumberFormattingTextWatcher - 它不这样做,你描述的格式,但话又说回来,你不必做很多工作来使用它。
As an alternative, you could just use PhoneNumberFormattingTextWatcher -- it doesn't do the formatting that you described, but then again you don't have to do much to use it.
这篇关于在自动的EditText格式的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!