方法一:
获取 EditText 的一个实例:
EditText myEdit = (EditText) findViewById(R.id.edittext1);
然后获取当前正在显示的字符串:
String phoneNumber = myEdit.getText().toString();
如果你想匹配的只是它的初始数字,那么你可以按如下方式进行比较:
String initialPart = phoneNumber.substring(0, 4);
//Get 1st three characters and then compare it with 639
boolean valid = initialPart.equals("639");
然后您可以继续进行其他比较。但是,这种方法容易出错,您可能会错过一些极端情况。所以我建议选择方法2:
方法:2
不过,另一种非常好的方法是使用 Google 的 libphonenumber 库。文档说:
It is for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphone.
我用它来验证电话号码。它非常易于使用,您不需要照顾角落的情况。它考虑了您的国家/地区以及用户可能输入的各种格式。它检查该号码是否对该地区有效。它还处理用户可能输入的所有可能的有效格式,例如:
"+xx(xx)xxxx-xxxx", "+x.xxx.xxx.xxx","+1(111)235-READ" ,"+1/234/567/8901", "+1-234-567-8901 x1234"(这里 x 是数字)。
以下是如何验证它的示例用法:
PhoneNumber NumberProto = null;
String NumberStr = "639124463869"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
NumberProto = phoneUtil.parse(NumberStr, "CH");
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
boolean isValid = phoneUtil.isValidNumber(NumberProto); // returns true or false
P.S:"CH" 是瑞士的国家代码。您可以根据需要输入您的国家/地区代码。他们被给予here。希望能帮助到你。