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

Ami*_*mar 10 formatting android phone-number android-edittext

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

1(515)555-5555

我不希望用户在输入数字时输入"(",")"或" - "; 我希望自动添加这些字符.

例如,假设用户输入1- 应自动添加"1"后的括号,以便显示"1(".我希望在删除时具有类似的功能.

我试图在接口afterTextChanged方法中设置文本onTextWatcher,但它不起作用; 相反,它导致错误.任何帮助将不胜感激.

Nay*_*pte 11

你可以试试

editTextPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Run Code Online (Sandbox Code Playgroud)

检查PhoneNumnerFormattingTextWatxher

如果你想要自己的TextWatcher实现,那么你可以使用folling appraoch:

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

}
Run Code Online (Sandbox Code Playgroud)


小智 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;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以使用PhoneNumberFormattingTextWatcher - 它不会执行您所描述的格式化,但是再次使用它不需要做太多.