在EditText中自动格式化电话号码

10
在我的应用中,用户必须在一个EditText字段中输入电话号码,并使用以下格式:

1(515)555-5555

我不希望用户在输入号码时键入"("、")"或"-",我想让这些字符自动添加。
例如,假设用户输入了1 - 在"1"后面自动添加括号,以便显示为"1("。在删除时也希望有类似的功能。
我已经尝试在onTextWatcher接口的afterTextChanged方法中设置文本,但它不起作用;相反,它会导致错误。非常感谢任何帮助。

能否提供你的 afterTextChanged 代码和错误日志,这将非常有帮助。没有这些信息,很难确定问题所在(尽管我还是会猜测一下)。 - Mike
2个回答

11

你可以尝试

editTextPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

请查看PhoneNumnerFormattingTextWatxher

如果您想要自己实现TextWatcher,则可以使用以下方法:

import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;

/**
* Set this TextWatcher to EditText for Phone number
* formatting.
* 
* Along with this EditText should have
* 
* inputType= phone
* 
* maxLength=14    
*/
public class MyPhoneTextWatcher extends PhoneNumberFormattingTextWatcher {

private EditText editText;

/**
 * 
 * @param EditText
 *            to handle other events
 */
public MyPhoneTextWatcher(EditText editText) {
    // TODO Auto-generated constructor stub
    this.editText = editText;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    super.onTextChanged(s, start, before, count);

    //--- write your code here
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub
    super.beforeTextChanged(s, start, count, after);
}

@Override
public synchronized void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    super.afterTextChanged(s);
}

}

10

你可能会遇到问题,因为afterTextChanged是可重入的,也就是说对文本所做的更改会导致再次调用该方法。

如果这是问题所在,一个解决方法是保持一个实例变量标志:

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;
       }
    }
}

作为替代方案,你可以使用PhoneNumberFormattingTextWatcher -- 它不会执行你描述的格式化操作,但是使用它并不需要太多工作。


非常感谢Mike,根据您的建议实施后,现在它运行良好。 - Amit Kumar
这个方法可行,但有些棘手。对于我的格式问题,我需要确保重新格式化代码以光标回到原位结束(setSelection()),否则重写文本将导致光标始终移动到开头(这是一个令人沮丧的界面)。 - David Pisoni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接