电话号码格式化Android中的EditText

时间:2013-03-26 21:01:16

标签: android

我正在创建一个简单的地址簿应用程序(目标为4.2),其中包含姓名,地址,城市,州,邮编和电话。

我想将电话号码输入格式化为电话号码(XXX)XXX-XXXX,但我需要将值拉出为字符串,以便在保存时将其存储在我的数据库中。我怎样才能做到这一点?? 我将EditText设置为“电话号码”输入,但显然不会做太多。

16 个答案:

答案 0 :(得分:83)

只需使用PhoneNumberFormattingTextWatcher,只需致电:

editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

<强>加成
需要说明的是,PhoneNumberFormattingTextWatcher的backbone是PhoneNumberUtils类。区别在于TextWatcher维护EditText,而每次更改内容时都必须调用PhoneNumberUtils.formatNumber()

答案 1 :(得分:48)

有一个名为PhoneNumberUtils的图书馆可以帮助您应对电话号码转换和比较。例如,使用......

EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())

...以标准格式格式化您的号码。

PhoneNumberUtils.compare(String a, String b);

...有助于模糊比较。还有很多。查看http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html了解更多信息。

P.S。将EditText设置为phone已经是一个不错的选择;最后添加digits可能会有所帮助,例如在你的布局中它看起来像......

<EditText
    android:id="@+id/editTextId"
    android:inputType="phone"
    android:digits="0123456789+" 
/> 

答案 2 :(得分:21)

只需使用:

在Java代码中:

editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

在XML代码中:

<EditText
    android:id="@+id/etPhoneNumber"
    android:inputType="phone"/>

此代码适合我。在编辑文本中更改文本时,它会自动格式化。

答案 3 :(得分:19)

我最近做了类似的格式,如1(XXX)XXX-XXXX for Android EditText。请在下面找到代码。只需使用TextWatcher子类作为文本更改的侦听器: ....

UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(
            new WeakReference<EditText>(mYourEditText));
    mYourEditText.addTextChangedListener(addLineNumberFormatter);

...

private class UsPhoneNumberFormatter implements TextWatcher {
    //This TextWatcher sub-class formats entered numbers as 1 (123) 456-7890
    private boolean mFormatting; // this is a flag which prevents the
                                    // stack(onTextChanged)
    private boolean clearFlag;
    private int mLastStartLocation;
    private String mLastBeforeText;
    private WeakReference<EditText> mWeakEditText;

    public UsPhoneNumberFormatter(WeakReference<EditText> weakEditText) {
        this.mWeakEditText = weakEditText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        if (after == 0 && s.toString().equals("1 ")) {
            clearFlag = true;
        }
        mLastStartLocation = start;
        mLastBeforeText = s.toString();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // TODO: Do nothing
    }

    @Override
    public void afterTextChanged(Editable s) {
        // Make sure to ignore calls to afterTextChanged caused by the work
        // done below
        if (!mFormatting) {
            mFormatting = true;
            int curPos = mLastStartLocation;
            String beforeValue = mLastBeforeText;
            String currentValue = s.toString();
            String formattedValue = formatUsNumber(s);
            if (currentValue.length() > beforeValue.length()) {
                int setCusorPos = formattedValue.length()
                        - (beforeValue.length() - curPos);
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            } else {
                int setCusorPos = formattedValue.length()
                        - (currentValue.length() - curPos);
                if(setCusorPos > 0 && !Character.isDigit(formattedValue.charAt(setCusorPos -1))){
                    setCusorPos--;
                }
                mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
            }
            mFormatting = false;
        }
    }

    private String formatUsNumber(Editable text) {
        StringBuilder formattedString = new StringBuilder();
        // Remove everything except digits
        int p = 0;
        while (p < text.length()) {
            char ch = text.charAt(p);
            if (!Character.isDigit(ch)) {
                text.delete(p, p + 1);
            } else {
                p++;
            }
        }
        // Now only digits are remaining
        String allDigitString = text.toString();

        int totalDigitCount = allDigitString.length();

        if (totalDigitCount == 0
                || (totalDigitCount > 10 && !allDigitString.startsWith("1"))
                || totalDigitCount > 11) {
            // May be the total length of input length is greater than the
            // expected value so we'll remove all formatting
            text.clear();
            text.append(allDigitString);
            return allDigitString;
        }
        int alreadyPlacedDigitCount = 0;
        // Only '1' is remaining and user pressed backspace and so we clear
        // the edit text.
        if (allDigitString.equals("1") && clearFlag) {
            text.clear();
            clearFlag = false;
            return "";
        }
        if (allDigitString.startsWith("1")) {
            formattedString.append("1 ");
            alreadyPlacedDigitCount++;
        }
        // The first 3 numbers beyond '1' must be enclosed in brackets "()"
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append("("
                    + allDigitString.substring(alreadyPlacedDigitCount,
                            alreadyPlacedDigitCount + 3) + ") ");
            alreadyPlacedDigitCount += 3;
        }
        // There must be a '-' inserted after the next 3 numbers
        if (totalDigitCount - alreadyPlacedDigitCount > 3) {
            formattedString.append(allDigitString.substring(
                    alreadyPlacedDigitCount, alreadyPlacedDigitCount + 3)
                    + "-");
            alreadyPlacedDigitCount += 3;
        }
        // All the required formatting is done so we'll just copy the
        // remaining digits.
        if (totalDigitCount > alreadyPlacedDigitCount) {
            formattedString.append(allDigitString
                    .substring(alreadyPlacedDigitCount));
        }

        text.clear();
        text.append(formattedString.toString());
        return formattedString.toString();
    }

}

答案 4 :(得分:9)

也许以下示例项目可以帮助您;

https://github.com/reinaldoarrosi/MaskedEditText

该项目包含一个视图类调用MaskedEditText。首先,您应该在项目中添加

然后在项目的res / values / attrs.xml文件中添加以下xml部分;

<resources>
    <declare-styleable name="MaskedEditText">
        <attr name="mask" format="string" />
        <attr name="placeholder" format="string" />
    </declare-styleable>
</resources>

然后您就可以使用MaskedEditText视图。

最后,您应该在xml文件中添加MaskedEditText,如下所示;

<packagename.currentfolder.MaskedEditText
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/maskedEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="5"
    app:mask="(999) 999-9999"
    app:placeholder="_" >

当然,您可以通过编程方式使用它。

完成这些步骤后,添加MaskedEditText将如下所示;

enter image description here

以编程方式,如果您想将其文本值视为未屏蔽,则可以使用以下行;

maskedEditText.getText(true);

要获取屏蔽值,您可以在false方法中发送true值而不是getText值。

答案 5 :(得分:3)

//(123) 456 7890  formate set

private int textlength = 0;

public class MyPhoneTextWatcher implements TextWatcher {

    @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();
        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 || textlength == 10) {
            etMobile.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
            etMobile.setSelection(etMobile.getText().length());
        }

    }
    @Override
    public void afterTextChanged(Editable editable) {
    }
}

答案 6 :(得分:2)

您可以使用带有模式匹配的正则表达式从字符串中提取数字。

    String s="";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher("(1111)123-456-789"); //editText.getText().toString()                                      
    while (m.find()) {
    s=s+m.group(0);
    }
    System.out.println("............"+s);    

    Output : ............1111123456789

答案 7 :(得分:2)

按照本答案中的说明格式化EditText蒙版。

  

https://stackoverflow.com/a/34907607/1013929

之后,您可以使用以下命令从掩码字符串中捕获原始数字:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

答案 8 :(得分:1)

不要担心。我为您提供了更好的解决方案。你可以在下面看到这个简单的应用程序链接。

private EditText mPasswordField;
public int textLength = 0;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mPasswordField = (EditText) findViewById(R.id.password_field);
    mPasswordField.addTextChangedListener(this);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

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


    String text = mPasswordField.getText().toString();
    textLength = mPasswordField.getText().length();

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

    if (textLength == 1) {
        if (!text.contains("(")) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());
        }

    } else if (textLength == 5) {

        if (!text.contains(")")) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());
        }

    } else if (textLength == 6) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());

    } else if (textLength == 10) {
        if (!text.contains("-")) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());
        }
    } else if (textLength == 15) {
        if (text.contains("-")) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());
        }
    }else if (textLength == 18) {
        if (text.contains("-")) {
            mPasswordField.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
            mPasswordField.setSelection(mPasswordField.getText().length());
        }
    } else if (textLength == 20) {
        Intent i = new Intent(MainActivity.this, Activity2.class);
        startActivity(i);

    }



}

@Override
public void afterTextChanged(Editable s) {

}

不:不要忘记&#34;实施TextWatcher&#34;与您的活动类。

链接:https://drive.google.com/open?id=0B-yo9VvU7jyBMjJpT29xc2k5bnc

希望你对这个解决方案感到很酷。

答案 9 :(得分:1)

更像是干净的

this.route('user-profile', { 'path' : 'users/:id/profile' })

答案 10 :(得分:1)

如果您只对国际号码感兴趣,并且希望能够在输入中显示与国家/地区代码相匹配的国家/地区的标志,那么我为此编写了一个小库:

https://github.com/tfcporciuncula/phonemoji

外观如下:

library demo

答案 11 :(得分:0)

您只能使用Java代码接受数字和电话号码类型

 EditText number1 = (EditText) layout.findViewById(R.id.edittext); 
    number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
     number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
      number1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(14)}); // 14 is max digits

此代码将避免在读取输入后进行大量验证

答案 12 :(得分:0)

您可以使用衍生工具在Android中格式化电话号码。此解决方案比其他解决方案更好,因为它不会更改输入文本。格式保持纯视觉效果。

implementation 'com.googlecode.libphonenumber:libphonenumber:7.0.4'

格式化程序类:

open class PhoneNumberFormatter : TransformationMethod {
private val mFormatter: AsYouTypeFormatter = PhoneNumberUtil.getInstance().getAsYouTypeFormatter(Locale.getDefault().country)

override fun getTransformation(source: CharSequence, view: View): CharSequence {
    val formatted = format(source)
    if (source is Spannable) {
        setSpans(source, formatted)
        return source
    }
    return formatted
}
override fun onFocusChanged(view: View?, sourceText: CharSequence?, focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) = Unit

private fun setSpans(spannable: Spannable, formatted: CharSequence): CharSequence {

    spannable.clearSpawns()

    var charterIndex = 0
    var formattedIndex = 0
    var spawn = ""
    val spawns: List<String> = spannable
        .map {
            spawn = ""
            charterIndex = formatted.indexOf(it, formattedIndex)
            if (charterIndex != -1){
                spawn = formatted.substring(formattedIndex, charterIndex-1)
                formattedIndex = charterIndex+1
            }
            spawn
        }

    spawns.forEachIndexed { index, sequence ->
        spannable.setSpan(CharterSpan(sequence), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    return formatted
}

private fun Spannable.clearSpawns() =
    this
        .getSpans(0, this.length, CharterSpan::class.java)
        .forEach { this.removeSpan(it) }

private fun format(spannable: CharSequence): String {
    mFormatter.clear()
    var formated = ""
    for (i in 0 until spannable.length) {
        formated = mFormatter.inputDigit(spannable[i])
    }
    return formated
}

private inner class CharterSpan(private val charters: String) : ReplacementSpan() {

    var space = 0

    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        space = Math.round(paint.measureText(charters, 0, charters.length))
        return Math.round(paint.measureText(text, start, end)) + space
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
        space = Math.round(paint.measureText(charters, 0, charters.length))
        canvas.drawText(text, start, end, x + space, y.toFloat(), paint)
        canvas.drawText(charters, x, y.toFloat(), paint)
    }
    }

}

用法:

editText.transformationMethod = formatter

答案 13 :(得分:0)

您需要创建一个类:

public class PhoneTextFormatter implements TextWatcher {

    private final String TAG = this.getClass().getSimpleName();

    private EditText mEditText;

    private String mPattern;

    public PhoneTextFormatter(EditText editText, String pattern) {
        mEditText = editText;
        mPattern = pattern;
        //set max length of string
        int maxLength = pattern.length();
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        StringBuilder phone = new StringBuilder(s);

        Log.d(TAG, "join");

        if (count > 0 && !isValid(phone.toString())) {
            for (int i = 0; i < phone.length(); i++) {
                Log.d(TAG, String.format("%s", phone));
                char c = mPattern.charAt(i);

                if ((c != '#') && (c != phone.charAt(i))) {
                    phone.insert(i, c);
                }
            }

            mEditText.setText(phone);
            mEditText.setSelection(mEditText.getText().length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private boolean isValid(String phone)
    {
        for (int i = 0; i < phone.length(); i++) {
            char c = mPattern.charAt(i);

            if (c == '#') continue;

            if (c != phone.charAt(i)) {
                return false;
            }
        }

        return true;
    }
}

按如下所示使用它:

phone = view.findViewById(R.id.phone);
phone.addTextChangedListener(new PhoneTextFormatter(phone, "+7 (###) ###-####"));

答案 14 :(得分:0)

TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String CountryID= manager.getSimCountryIso().toUpperCase();
try{
    PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber pn1 = pnu.parse("99", CountryID);
    String pnE1641 = pnu.format(pn1, PhoneNumberUtil.PhoneNumberFormat.E164);
    code = pnE1641.substring(0, pnE1641.length()-2);
    codeLength  = code.length();
    Log.e("dfdsfdsfsdfsdf", "onCreate: "+codeLength);

}catch (Exception e){
    Log.e("dfdsfdsfsdfsdf", "onCreate: "+e);
}

phoneEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        int digits = phoneEditText.getText().toString().length();
        if (digits > 1)
            lastChar = phoneEditText.getText().toString().substring(digits-1);
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int digits = phoneEditText.getText().toString().length();
        Log.d("LENGTH",""+digits);
        if (!lastChar.equals("-")) {
            if (digits == codeLength+6) {
                phoneEditText.append("-");
            }
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
        if (!s.toString().startsWith("("+code+") ")) {
            phoneEditText.setText("("+code+") ");
            Selection.setSelection(phoneEditText.getText(), phoneEditText.getText().length());
        }
    }
});

答案 15 :(得分:0)

此代码适用于 (216) 555-5555

etphonenumber.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 = etphonenumber.getText().toString();
                int  textLength = etphonenumber.getText().length();
                if (text.endsWith("-") || text.endsWith(" ") || text.endsWith(" "))
                    return;
                if (textLength == 1) {
                    if (!text.contains("("))
                    {
                        etphonenumber.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                        etphonenumber.setSelection(etphonenumber.getText().length());
                    }
                }
                else if (textLength == 5)
                {
                    if (!text.contains(")"))
                    {
                        etphonenumber.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                        etphonenumber.setSelection(etphonenumber.getText().length());
                    }
                }
                else if (textLength == 6)
                {
                    etphonenumber.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
                    etphonenumber.setSelection(etphonenumber.getText().length());
                }
                else if (textLength == 10)
                {
                    if (!text.contains("-"))
                    {
                        etphonenumber.setText(new StringBuilder(text).insert(text.length() - 1, "-").toString());
                        etphonenumber.setSelection(etphonenumber.getText().length());
                    }
                }
            }
        });