一.国家选择并获取国家码
依赖包:implementation'com.hbb20:ccp:2.2.9'
界面:
<com.hbb20.CountryCodePicker
android:id="@+id/ccp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:layout_gravity="center_vertical"
app:ccp_arrowColor="@color/white"
app:ccp_contentColor="@color/white"
android:layout_marginLeft="5dp"
app:ccp_showFullName="false"
app:ccp_showNameCode="false" app:ccp_defaultNameCode="CN"
app:ccp_showPhoneCode="true"
app:ccp_textSize="16sp" />
代码:
选中监听:
ccp.setOnCountryChangeListener(() ->
countryCode = ccp.getSelectedCountryCode());
二.手机号验证
下载libphonenumber jar包到libs文件下,并引用
github地址:https://github.com/google/libphonenumber
使用方式如下:
public boolean isPhoneNumberValid(String phoneNumber, String countryCode) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(this);
try {
int code = Integer.parseInt(countryCode); long phone = Long.parseLong(phoneNumber);
Phonenumber.PhoneNumber pn = new Phonenumber.PhoneNumber();
pn.setCountryCode(code);
pn.setNationalNumber(phone);
return phoneUtil.isValidNumber(pn);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}