15

我有一个 EditText 视图,我希望它将用户的输入格式化为电话号码格式。例如,当用户输入 1234567890 时,只要输入前 3 个数字,EditText 视图就会动态地将其显示为“(123) 456-7890”。

我在我的 OnCreate 中尝试了以下操作,但它似乎对我没有任何作用......

EditText ET = (EditText) findViewById(R.id.add_number);
ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

如何让用户的输入以电话号码格式显示?

4

8 回答 8

44

使用此代码,您可以制作自定义 TextWatcher 并制作您想要的任何格式:

ET.addTextChangedListener(new PhoneNumberFormattingTextWatcher() {
        //we need to know if the user is erasing or inputing some new character
        private boolean backspacingFlag = false;
        //we need to block the :afterTextChanges method to be called again after we just replaced the EditText text
        private boolean editedFlag = false;
        //we need to mark the cursor position and restore it after the edition
        private int cursorComplement;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //we store the cursor local relative to the end of the string in the EditText before the edition
            cursorComplement = s.length()-ET.getSelectionStart();
            //we check if the user ir inputing or erasing a character
            if (count > after) {
                backspacingFlag = true;
            } else {
                backspacingFlag = false;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // nothing to do here =D
        }

        @Override
        public void afterTextChanged(Editable s) {
            String string = s.toString();
            //what matters are the phone digits beneath the mask, so we always work with a raw string with only digits
            String phone = string.replaceAll("[^\\d]", "");

            //if the text was just edited, :afterTextChanged is called another time... so we need to verify the flag of edition
            //if the flag is false, this is a original user-typed entry. so we go on and do some magic
            if (!editedFlag) {

                //we start verifying the worst case, many characters mask need to be added
                //example: 999999999 <- 6+ digits already typed
                // masked: (999) 999-999
                if (phone.length() >= 6 && !backspacingFlag) {
                    //we will edit. next call on this textWatcher will be ignored
                    editedFlag = true;
                    //here is the core. we substring the raw digits and add the mask as convenient
                    String ans = "(" + phone.substring(0, 3) + ") " + phone.substring(3,6) + "-" + phone.substring(6);
                    ET.setText(ans);
                    //we deliver the cursor to its original position relative to the end of the string
                    ET.setSelection(ET.getText().length()-cursorComplement);

                //we end at the most simple case, when just one character mask is needed
                //example: 99999 <- 3+ digits already typed
                // masked: (999) 99
                } else if (phone.length() >= 3 && !backspacingFlag) {
                    editedFlag = true;
                    String ans = "(" +phone.substring(0, 3) + ") " + phone.substring(3);
                    ET.setText(ans);
                    ET.setSelection(ET.getText().length()-cursorComplement);
                }
            // We just edited the field, ignoring this cicle of the watcher and getting ready for the next
            } else {
                editedFlag = false;
            }
        }
    });

确保将 XML 中的 EditText 长度限制为 14 个字符

<EditText
    android:id="@+id/editText_phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:lines="1"
    android:maxLength="14"/>
于 2016-01-20T18:21:24.993 回答
10

第 1 步:这里是 XML 文件中输入字段的代码。

 <EditText
    android:id="@+id/editText_phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:lines="1"
    android:maxLength="14"/>

第 2 步:这是添加到 MainFile.java 中的代码

 phoneNo = (EditText)findViewById(R.id.editText_phone);
 phoneNo.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

输出:它会给你像 (123)456-7890 这样的数字

于 2016-12-23T18:18:41.527 回答
5

尝试这个

PhoneNumberFormattingTextWatcher() 方法不起作用我尝试分配最后我得到了解决方案

  1. 在你的 xml 文件中粘贴这个

    <EditText
    android:id="@+id/editTextId"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:inputType="phone"
    android:digits="0123456789+" />
    
  2. 在你的 oncreate 方法中粘贴这个

    final EditText editText = (EditText) findViewById(R.id.editTextId);
    editText.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            // TODO Auto-generated method stub
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            // TODO Auto-generated method stub
        }
        @Override
        public void afterTextChanged(Editable s)
        {
            String text = editText.getText().toString();
            int  textLength = editText.getText().length();
            if (text.endsWith("-") || text.endsWith(" ") || text.endsWith(" "))
                return;
            if (textLength == 1) {
                if (!text.contains("("))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 5)
            {
                if (!text.contains(")"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 6)
            {
                editText.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                editText.setSelection(editText.getText().length());
            }
            else if (textLength == 10)
            {
                if (!text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 15)
            {
                if (text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
            else if (textLength == 18)
            {
                if (text.contains("-"))
                {
                    editText.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                    editText.setSelection(editText.getText().length());
                }
            }
        }
    });
    

输出:- 在此处输入图像描述

于 2017-07-19T07:39:23.020 回答
2

我做了一些事情,我将输入类型修改为电话,然后我使用正则表达式删除所有非数字字符: phonenumber = phonenumber.replaceAll("\D", "");

于 2013-02-04T19:01:46.060 回答
0

在您的布局中,将输入模式设置为“电话”

http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputMethod http://developer.android.com/reference/android/text/InputType.html#TYPE_CLASS_PHONE

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone" />

如果这不太适合您的需要,请在您的 EditText 中添加一个侦听器,并在每次击键时手动设置文本格式。

    editText.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                // format your EditText here
            }
            return false;
        }
    });
于 2013-02-04T18:19:56.970 回答
0

在您的 Java 代码中,您可以使用

yourEditText.setInputType(InputTytpe.TYPE_CLASS_PHONE)

或在你的 xml

android:inputType="phone"

爪哇

XML

于 2013-02-04T18:23:33.247 回答
0

请找到以下代码:
我使用TextWatcher接口将输入的电话号码动态格式化为(XXX)XXX-XXXX。

UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(edittxtPhoneNo);
edittxtPhoneNo.addTextChangedListener(addLineNumberFormatter);  


public class UsPhoneNumberFormatter implements TextWatcher {
    private EditText etMobile;

    public UsPhoneNumberFormatter(EditText edt) {
        etMobile = edt;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        String text = etMobile.getText().toString();
        int textlength = etMobile.getText().length();

        if (text.endsWith(" "))
            return;

        if (textlength == 1) {
            if (!text.contains("(")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 5) {
            if (!text.contains(")")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 6) {
            if (!text.contains(" ")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        } else if (textlength == 10) {
            if (!text.contains("-")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                etMobile.setSelection(etMobile.getText().length());
            }
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
    }
}
于 2018-06-05T07:35:25.160 回答
-7

您可以使用 JQuery validate(onkeyup 事件)来执行此操作,这样您就可以在输入时进行动态格式化(在那里考虑的不愉快体验) - 或者您可以使用 MVVM 库(例如 RAZOR 或 KnockoutJS)来执行此操作(当它们退出该字段时) .

JQuery Validate 文档站点和淘汰赛 JS 站点都提供了您想要做的示例。

于 2013-02-04T18:13:32.317 回答