【问题标题】:Automatically format phone number in EditText在 EditText 中自动格式化电话号码
【发布时间】:2011-02-21 10:04:18
【问题描述】:

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

1(515)555-5555

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

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

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

【问题讨论】:

  • 查看afterTextChanged 的代码和错误日志会非常有帮助。没有这些,很难确定问题出在哪里(尽管我还是会猜测一下)。

标签: android formatting android-edittext phone-number


【解决方案1】:

你可以试试

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

}

【讨论】:

    【解决方案2】:

    您可能会遇到问题,因为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 - 它不会执行您所描述的格式设置,但同样您无需做太多即可使用它。

    【讨论】:

    • 非常感谢迈克,在实施你的建议后它工作正常。
    • 这行得通,但很棘手。对于我的格式化问题,我需要确保重新格式化代码以向后移动光标(setSelection())结束,否则重写文本将导致光标总是移动到开头(这是一个令人沮丧的界面。)跨度>
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多