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

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

1(515)555-5555

我不希望用户在输入数字时键入“(”、“)”或“-”;我希望自动添加这些字符。

例如,假设用户键入 1 -- 应该自动添加“1”后面的括号,以便显示“1(”。我希望有类似的功能同时删除。

我曾尝试在onTextWatcher接口(interface)的afterTextChanged方法中设置文本,但不起作用;相反,它会导致错误。任何帮助将不胜感激。

最佳答案

你可以试试

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

}

https://stackoverflow.com/questions/5064576/

相关文章:

formatting - 如何使用 LaTeX 以实用程序员系列丛书的风格格式化源代码列表?

postgresql - 我可以在 PostgreSQL 中获得 CSV header 但没有行数吗

c++ - ostream showbase 不显示 "0x"为零值

ide - 为什么 IDE 不支持动态格式化?

java - 是否可以使用 String.format 作为条件小数点?

formatting - 抑制 Fortran 95 写入语句中的换行符

c# - microsoft.interop.excel 格式化单元格

java - 如何在 IntelliJ 中停止流式 API 的扁平化

javascript - 并非所有浏览器都支持 toLocaleString()?

io - Fortran 将我的输出添加到星号 - 为什么?