我正在开发一个应用程序,我希望以美国格式设置电话号码,例如xxx-xxx-xxxx
。我怎样才能做到这一点?
答案 0 :(得分:6)
尝试实现以下代码,然后在输入数字
时会出现“ - ” text.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
boolean flag = true;
String eachBlock[] = text.getText().toString().split("-");
for (int i = 0; i < eachBlock.length; i++)
{
if (eachBlock[i].length() > 3)
{
Log.v("11111111111111111111","cc"+flag + eachBlock[i].length());
}
}
if (flag) {
text.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
if (((text.getText().length() + 1) % 4) == 0)
{
if (text.getText().toString().split("-").length <= 2)
{
text.setText(text.getText() + "-");
text.setSelection(text.getText().length());
}
}
a = text.getText().toString();
}
else
{
a = text.getText().toString();
keyDel = 0;
}
} else {
text.setText(a);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void afterTextChanged(Editable s) {
}
});
答案 1 :(得分:1)
您需要更改区域设置(设置 - &gt;区域设置和文字 - &gt;选择区域设置)
否则希望此链接有用
http://androidforums.com/g1-support/39788-contact-numbers-us-format-uk.html
答案 2 :(得分:1)
http://code.google.com/p/libphonenumber/
试试这个来处理电话号码。它支持格式化国家/国际电话号码,如您所愿。
答案 3 :(得分:0)
mobileEditText.addTextChangedListener(观察者); 使用以下功能..
private final TextWatcher watcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
mAfter = after;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s) {
if (!mFormatting) {
mFormatting = true;
if(mAfter!=0) // in case back space ain't clicked...
PhoneNumberUtils.formatNumber(s,PhoneNumberUtils.getFormatTypeForLocale(Locale.US));
mFormatting = false;
}