【Android】如何选择多个国家并验证多个国家的手机号码

一.国家选择并获取国家码

依赖包: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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容