简体   繁体   English

Android-在EditText中格式化电话号码

[英]Android - Formatting phone number in EditText

I need a little assistance making this to work, because server side API requires special format for phone number field. 我需要一点帮助使其工作,因为服务器端API需要电话号码字段的特殊格式。 Maybe I could edit that field just before sending API request by replacing characters at specific positions, however that would still give the user freedom to insert wrong format for phone number. 也许我可以在发送API请求之前通过在特定位置替换字符来编辑该字段,但是这仍然使用户可以自由地为电话号码插入错误的格式。 I need to make EditText assist him just right after he changed the text and direct him to right format. 在他更改文本并将其定向为正确格式之后,我需要立即使EditText协助他。

For that I have used TextWatcher method afterTextChanged() and format which I need is next: (063)22-22-333 为此,我使用了TextWatcher方法afterTextChanged() ,接下来需要使用的格式是(063)22-22-333

This is what I have tried: 这是我尝试过的:

private static final char space = '-';
private static final char brackets = '(';
private static final char brackets1 = ')';

etPhone.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // (063)22-22-333

            // -> Error

            if (s.length() > 0 && !s.toString().startsWith("(")) {
                s.replace(0, s.length(), "(0");
            }

            if (s.length() > 0 && s.length() == 8) {
                final char c = s.charAt(s.length() - 1);
                if (space == c) {
                    s.delete(s.length() - 1, s.length());
                }
            } else if (s.length() > 0 && s.length() == 5) {
                final char c = s.charAt(s.length() - 1);
                if (brackets1 == c) {
                    s.delete(s.length() - 1, s.length());
                }
            }

            // Insert char where needed.
            if (s.length() > 0 && s.length() == 8) {
                char c = s.charAt(s.length() - 1);
                // Only if its a digit where there should be a space we insert a space
                if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 7) {
                    s.insert(s.length() - 1, String.valueOf(space));
                }
            } else if (s.length() > 0 && s.length() == 5) {
                char c = s.charAt(s.length() - 1);
                if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(brackets1)).length <= 4) {
                    s.insert(s.length() - 1, String.valueOf(brackets1));
                }
            }
        }
    });

I'm getting an error after writing 4 character. 写4个字符后出现错误。 Error is showing at the beginning. 开头显示错误。

You are using the split() method which needs as its 2nd parameter a regular expression and here is your problem: you need to escape "(" and ")" in regular expressions. 您正在使用split()方法,该方法需要一个正则表达式作为其第二个参数,这是您的问题:您需要在正则表达式中转义“(”和“)”。 So I made some changes: 因此,我进行了一些更改:

private static final char space = '-';
private static final char brackets = '(';
private static final char brackets1 = ')';
private static final String sspace = "\\x32";
private static final String sbrackets = "\\x28";
private static final String sbrackets1 = "\\x29";

    etPhone.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            // (063)22-22-333

            // -> Error

            if (s.length() > 0 && !s.toString().startsWith("(")) {
                s.replace(0, s.length(), "(0");
            }

            if (s.length() > 0 && s.length() == 8) {
                final char c = s.charAt(s.length() - 1);
                if (space == c) {
                    s.delete(s.length() - 1, s.length());
                }
            } else if (s.length() > 0 && s.length() == 5) {
                final char c = s.charAt(s.length() - 1);
                if (brackets1 == c) {
                    s.delete(s.length() - 1, s.length());
                }
            }

            // Insert char where needed.
            if (s.length() > 0 && s.length() == 8) {
                char c = s.charAt(s.length() - 1);
                // Only if its a digit where there should be a space we insert a space
                if (Character.isDigit(c) && TextUtils.split(s.toString(), sspace).length <= 7) {
                    s.insert(s.length() - 1, String.valueOf(space));
                }
            } else if (s.length() > 0 && s.length() == 5) {
                char c = s.charAt(s.length() - 1);
                if (Character.isDigit(c) && TextUtils.split(s.toString(), sbrackets1).length <= 4) {
                    s.insert(s.length() - 1, String.valueOf(brackets1));
                }
            }
        }
    });

Now you get no crash after the 3d char. 现在,在3d字符之后您不会崩溃。
Every time you want to use split() instead of String.valueOf(brackets1) use brackets1 or sbrackets or sspace 每次您要使用split()而不是String.valueOf(brackets1)使用brackets1sbracketssspace

You might have an easier time converting from a common format to the format that the server side is expecting. 从通用格式转换为服务器端期望的格式可能会更容易。 To get to a standard format, there are a couple of classes which already exist that might help you. 为了达到标准格式,已经存在一些可以帮助您的类。 Have you looked at PhoneNumberFormattingTextWatcher ? 您看过PhoneNumberFormattingTextWatcher吗?

If you absolutely need to use your own watcher, there are other utils that can help you: 如果您绝对需要使用自己的观察程序,则还有其他实用程序可以帮助您:

// this will result in the string "(212) 555-2232"
String number = PhoneNumberUtils.formatNumber("2125552232", "US")

After getting a predictable result, it should be trivial to convert to whatever your server needs. 在获得可预测的结果之后,转换为服务器所需的内容应该很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM