gpt4 book ai didi

android - android中的电话号码格式

转载 作者:太空狗 更新时间:2023-10-29 16:05:52 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个 editText 可以接受用户的电话号码,我的目标是,一旦用户输入电话号码,它就应该被格式化(就像在文本更改的监听器上应用一样),格式就像 XXX-XXX-XXXX.

我把代码写成

ePhone.addTextChangedListener(new TextWatcher() {

private Pattern pattern;
private Matcher matcher;
String a;


@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub

boolean flag = true;
if (flag) {

if (((ePhone.getText().length() + 1) % 4) == 0)
{
if (ePhone.getText().toString().split("-").length <= 2)
{
ePhone.setText(ePhone.getText() + "-");
ePhone.setSelection(ePhone.getText().length());
}
}
a = ePhone.getText().toString();
} else {
ePhone.setText(a);
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stus

}
});

但是当用户想要从此 editText 中删除一个数字时,它无法正常工作。提前致谢。

最佳答案

假设您想按照美国格式格式化电话号码。

+1 (###) ###-####,1 (###) ###-####,###-####,###-###-####,011 $

以下将有助于您的目的:

phoneEditText.addTextChangedListener(new TextWatcher() {
private boolean mFormatting; // a flag that prevents stack overflows.
private int mAfter;

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

//called before the text is changed...
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mAfter = after; // flag to detect backspace.
}

@Override
public void afterTextChanged(Editable s) {
// Make sure to ignore calls to afterTextChanged caused by the work done below
if (!mFormatting) {
mFormatting = true;
// using US formatting.
if(mAfter != 0) // in case back space ain't clicked.
PhoneNumberUtils.formatNumber(
s,PhoneNumberUtils.getFormatTypeForLocale(Locale.US));
mFormatting = false;
}
}
});

如果您需要特定于位置的服务,即对于每个位置,您需要该位置的特定格式(请参阅 this link )。如果你只需要你需要的格式,那么在上面代码 fragment 中的行的地方写一个自定义函数。

PhoneNumberUtils.formatNumber(
s, PhoneNumberUtils.getFormatTypeForLocale(Locale.US));

关于android - android中的电话号码格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15494093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com