电话号码在Android中格式化EditText
我正在制作一个简单的地址簿应用程序(定位4.2),其中需要名称,地址,城市,州,邮编和电话。
我想将input的电话号码格式化为电话号码(XXX)XXX-XXXX,但我需要将值作为string提取出来,以便在保存时将其存储在数据库中。 我怎样才能做到这一点?? 我有EditText设置为“电话号码”input,但显然不会做太多。
有一个名为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了解更多信息。;
ps将EditText设置为phone
已经是不错的select; 最终它可能会有帮助添加digits
例如在你看来的布局…
<EditText android:id="@+id/editTextId" android:inputType="phone" android:digits="0123456789+" />
只需使用PhoneNumberFormattingTextWatcher ,只需调用:
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
加成
要明确,PhoneNumberFormattingTextWatcher的骨干是PhoneNumberUtils类。 不同之处在于TextWatcher在每次更改其内容时都必须调用PhoneNumberUtils.formatNumber()
来维护EditText。
我最近为Android EditText做了类似1(XXX)XXX-XXXX的格式化。 请find下面的代码。 只需使用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(); } }
简单使用这个:
在Java代码中:
editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
在XML代码中:
<EditText android:id="@+id/etPhoneNumber" android:inputType="phone"/>
这个代码适合我。 当文本在编辑文本中改变时它会自动格式化。
也许下面的示例项目帮助你;
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
将如下所示;
以编程方式,如果你想把它的文本值作为非屏蔽,你可以使用下面的行;
maskedEditText.getText(true);
要获取屏蔽值,您可以在getText
方法中发送false
值而不是true
值。
您可以使用模式匹配的正则expression式从string中提取数字。
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
<EditText android:id="@+id/etnumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:digits="0123456789+" android:hint="Contact Number" />
按照本答复中的说明格式化EditText掩码。
在那之后,你可以用蒙面string捕捉原始数字:
String phoneNumbers = maskedString.replaceAll("[^\\d]", "");
别担心 我为你做了最好的解决scheme。 您可以在下面看到这个简单的应用
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) { }
不要:不要忘记用你的activity类来实现TextWatcher。
链接: https : //drive.google.com/open?id=0B-yo9VvU7jyBMjJpT29xc2k5bnc
希望你对这个解决scheme感觉很酷。
//(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) { } }