Code Monkey home page Code Monkey logo

android-phone-field's Introduction

android-phone-field

android-phone-field is A small UI library that allows you to create phone fields with corresponding country flags, and validate the phone number using libphonenumber from google.

alt text

The library has two different fields:

  • PhoneEditText : includes EditText alongside the flags spinner
  • PhoneInputLayout : includes a TextInputLayout from the design support library alongside the flags spinner

Features

  • Displays the correct country flag if the user enters a valid international phone number
  • Allows the user to choose the country manually and only enter a national phone number
  • Allows you to choose a default country, which the field will change to automatically if the user chose a different country then cleared the field.
  • Validates the phone number
  • Returns the valid phone number including the country code

Usage

In your module's gradle file add the following dependency, please make sure that you have jcenter in your repositories list

compile ('com.lamudi.phonefield:phone-field:0.1.3@aar') {
    transitive = true
}

In your layout you can use the PhoneInputLayout

<com.lamudi.phonefield.PhoneInputLayout
     android:id="@+id/phone_input_layout"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

or the PhoneEditText

 <com.lamudi.phonefield.PhoneEditText
     android:id="@+id/edit_text"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

Then in your Activity/Fragment

final PhoneInputLayout phoneInputLayout = (PhoneInputLayout) findViewById(R.id.phone_input_layout);
final PhoneEditText phoneEditText = (PhoneEditText) findViewById(R.id.edit_text);
final Button button = (Button) findViewById(R.id.submit_button);

// you can set the hint as follows
phoneInputLayout.setHint(R.string.phone_hint);
phoneEditText.setHint(R.string.phone_hint);

// you can set the default country as follows
phoneInputLayout.setDefaultCountry("DE");
phoneEditText.setDefaultCountry("FR");

button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    boolean valid = true;
    
    // checks if the field is valid 
    if (phoneInputLayout.isValid()) {
      phoneInputLayout.setError(null);
    } else {
      // set error message
      phoneInputLayout.setError(getString(R.string.invalid_phone_number));
      valid = false;
    }

    if (phoneEditText.isValid()) {
      phoneEditText.setError(null);
    } else {
      phoneEditText.setError(getString(R.string.invalid_phone_number));
      valid = false;
    }

    if (valid) {
      Toast.makeText(MainActivity.this, R.string.valid_phone_number, Toast.LENGTH_LONG).show();
    } else {
      Toast.makeText(MainActivity.this, R.string.invalid_phone_number, Toast.LENGTH_LONG).show();
    }
    
    // Return the phone number as follows
    String phoneNumber = phoneInputLayout.getPhoneNumber();
  }
});
 

Customization

In case the default style doesn't match your app styles, you can extend the PhoneInputLayout, or PhoneEditText and provide your own xml, but keep in mind that you have to provide a valid xml file with at least an EditText (tag = com_lamudi_phonefield_edittext) and Spinner (tag = com_lamudi_phonefield_flag_spinner), otherwise the library will throw an IllegalStateException.

You can also create your own custom view by extending the PhoneField directly.

Countries generation

For better performance and to avoid using json data and then parse it to be used in the library, a simple nodejs is used to convert the countries.json file in raw/countries-generator/ into a plain java utility class that has static list of countries.

The generation script works as follows:

node gen.js

or

./gen.js

Motivation

This is probably not the the first library with the same purpose, for instance before I started working on the library I came across IntlPhoneInput which provides almost most of the functionality this library provides, however I chose to develop a new library for the following reasons:

  • This library provides two implementations of PhoneField using EditText and TextInputLayout
  • This library allows users to extend the functionality and use custom layouts if needed to match the application theme
  • This library uses a static list of countries generated from the countries.json file in the raw resources

Attributions

  1. Inspired by intl-tel-input for jQuery and IntlPhoneInput
  2. Flag images from GoSquared
  3. Original country data from mledoze's World countries in JSON, CSV and XML which is then used to generate a plain Java file
  4. Formatting/validation using libphonenumber

android-phone-field's People

Contributors

fouadkada avatar ialmetwally avatar jamesgill avatar mateisuica avatar udan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-phone-field's Issues

new phone number support

In iran 0905 addend from irancell . and this repo validation dont accept this number like +98905XXXXXXX

Support night mode?

Hello,

Does this library support night mode?
IF yes how can we implement it and if no what should we do?

Because in dark mode we have as shown in the image below

image

allow backup

This libraty force me to set allowBackup true?!!

Execution failed for task ':main:processDebugMainManifest'.

Manifest merger failed : Attribute application@allowBackup value=(false) from AndroidManifest.xml:43:9-36
is also present at [com.lamudi.phonefield:phone-field:0.1.3] AndroidManifest.xml:12:9-35 value=(true).
Suggestion: add 'tools:replace="android:allowBackup"' to element at AndroidManifest.xml:41:5-459:19 to override.

NoSuchMethodError: No virtual method parseAndKeepRawInput

After adding another library using PhoneNumberUtils, I got massive crash:

java.lang.NoSuchMethodError: No virtual method parseAndKeepRawInput(Ljava/lang/String;Ljava/lang/String;)Lcom/google/i18n/phonenumbers/Phonenumber$PhoneNumber; in class Lcom/google/i18n/phonenumbers/PhoneNumberUtil; or its super classes (declaration of 'com.google.i18n.phonenumbers.PhoneNumberUtil' appears in /data/app/myapp-k09d0DyzNRI0pnj3Qg25Ww==/base.apk!classes33.dex)

Here:

        phoneNumberButton.setOnClickListener(new OnOneClickListener() {
            @Override
            public void onOneClick(View v) {
                String pattern = "^\\+[1-9]\\d{5,14}$";
                if (phoneInputLayout.getPhoneNumber().matches(pattern)) { // <--------
                    // doing something here
                } else {
                    phoneInputLayout.setError(getActivity().getResources().getString(R.string.bad_phone_number_format_error));
                }
            }
        });

Any advice? I am using your lib as:

    implementation('com.lamudi.phonefield:phone-field:0.1.3@aar') {
        transitive = true
    }

I added:

    implementation 'com.hbb20:ccp:2.7.3'

I have already tried putting this in proguard-rules.txt:

-keep public class com.google.i18n.phonenumbers.*
-keep public class com.lamudi.phonefield.*

Also, if I do this:

    implementation('com.lamudi.phonefield:phone-field:0.1.3') {
        include 'com.google.i18n.phonenumbers.*'
        transitive = true
    }

I get an error:

A problem occurred evaluating project ':app'.
> Could not find method include() for arguments [com.google.i18n.phonenumbers.*] on DefaultExternalModuleDependency{group='com.lamudi.phonefield', name='phone-field', version='0.1.3', configuration='default'} of type org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency.

Get country

Hi! Excelente library!

How I can get the country to set in the edittext the numbers according to the flag.

Can be automatic that in a update of the library...

Thanks!

setDefaultCountry problem

Hi,

I would like to know if this is a know issue, i'm trying to set the default country to "UAE" but doesn't work.
Other countries are working like France "FR"

Changing default UK to Iran

The default country is set to the United Kingdom on startup, how can I set it to my choice e.g Iran. Thanks

Tow way data binding

Hello,
I'm using your library and i want to get the mobile number from PhoneInputLayout using tow way data binding, bellow the code:

  1. layout :
<com.lamudi.phonefield.PhoneInputLayout
            android:id="@+id/phone_input_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="@={viewModel.phoneNumber}"
            android:visibility="@{viewModel.isPhoneNumberVisible ? View.VISIBLE : View.GONE}"
            android:textColorHint="@color/white"
            android:layout_marginRight="30dp"/>
  1. ViewModel:
    public ObservableField<String> phoneNumber = new ObservableField<>("");

i'm always getting Error:(18, 44) error: cannot find symbol class FragmentLoginBinding

Can you help please?

Crash on start over kotlin proyect

Using version 0.1.3 with:

  • kotlin: "1.2.21"
  • compileSdk: 26,
  • minSdk : 16,
  • buildTools: "26.0.2"
  • support Library: "27.0.1",
  • Google Play Services: "11.6.0",

If I put PhoneInputLayout or PhoneEditText in my layout I get an error on activity start:

Process: ..., PID: 19490
   java.lang.RuntimeException: Unable to start activity ComponentInfo{.../....screens.individual.signup.SignUpActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #71: Binary XML file line #71: Error inflating class com.lamudi.phonefield.PhoneInputLayout
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
       at android.app.ActivityThread.-wrap11(Unknown Source:0)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6541)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
    Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #71: Binary XML file line #71: Error inflating class com.lamudi.phonefield.PhoneInputLayout
    Caused by: android.view.InflateException: Binary XML file line #71: Binary XML file line #71: Error inflating class com.lamudi.phonefield.PhoneInputLayout
    Caused by: android.view.InflateException: Binary XML file line #71: Error inflating class com.lamudi.phonefield.PhoneInputLayout
    Caused by: java.lang.reflect.InvocationTargetException
       at java.lang.reflect.Constructor.newInstance0(Native Method)
       at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
       at android.view.LayoutInflater.createView(LayoutInflater.java:647)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
       at ....screens.individual.signup.SignUpFragment.onCreateView(SignUpFragment.kt:25)
       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2261)
       at android.support.v4.app.FragmentManagerImpl.ensureInflatedFragmentView(FragmentManager.java:1655)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1390)
       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1650)
       at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1906)
       at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3698)
       at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
       at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:350)
       at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
       at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
       at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
       at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)

Exception with new gradle version 3.1.3

I recently migrated to the latest gradle version on my android studio and was trying to build this library there. I am getting the following error while trying to build my project:
Program type already present: com.google.protobuf.AbstractMessageLite$Builder$LimitedInputStream

Here are my gradle imports:

`dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation project(':audioiolib')
implementation project(':cheetah-mobile-3.4.7')
// https://mvnrepository.com/artifact/commons-net/commons-net
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
transitive = true
}
implementation('com.crashlytics.sdk.android:answers:1.3.12@aar') {
transitive = true
}
implementation ('com.lamudi.phonefield:phone-field:0.1.3@aar') {
transitive = true
}
implementation files('libs/YouTubeAndroidPlayerApi.jar')
implementation "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
implementation "com.google.code.gson:gson:$rootProject.ext.gsonVersion"
implementation "com.android.support:design:$rootProject.ext.supportLibraryVersion"
implementation "com.android.support:support-v4:$rootProject.ext.supportLibraryVersion"
implementation "com.android.support:cardview-v7:$rootProject.ext.supportLibraryVersion"
implementation "com.android.support:recyclerview-v7:$rootProject.ext.supportLibraryVersion"
implementation "com.android.support:preference-v7:$rootProject.ext.supportLibraryVersion"
implementation "com.android.support:multidex:$rootProject.ext.multidexVersion"
implementation "com.google.firebase:firebase-crash:16.0.1"
implementation "com.google.firebase:firebase-core:16.0.1"
implementation "com.google.firebase:firebase-messaging:17.0.0"
implementation "com.google.firebase:firebase-ads:15.0.1"
implementation "com.google.firebase:firebase-config:16.0.0"
implementation "com.google.firebase:firebase-auth:16.0.1"
implementation "com.google.firebase:firebase-firestore:17.0.1"
implementation "com.google.android.gms:play-services-auth:15.0.1"
implementation "com.facebook.android:facebook-android-sdk:$rootProject.ext.facebookSDKVersion"
implementation "com.jakewharton:butterknife:$rootProject.ext.butterknifeVersion"
implementation "com.jakewharton.timber:timber:$rootProject.ext.timberVersion"
implementation "com.amazonaws:aws-android-sdk-core:$rootProject.ext.awsSDKVersion"
implementation "com.amazonaws:aws-android-sdk-s3:$rootProject.ext.awsSDKVersion"
implementation "com.amazonaws:aws-android-sdk-ddb:$rootProject.ext.awsSDKVersion"
implementation "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofitSDKVersion"
implementation "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofitSDKVersion"
implementation "com.squareup.picasso:picasso:$rootProject.ext.picassoSDKVersion"
implementation "io.branch.sdk.android:library:$rootProject.ext.branchVersion"
implementation "com.amazonaws:aws-android-sdk-ddb-mapper:$rootProject.ext.awsSDKVersion"
testImplementation "junit:junit:$rootProject.ext.junitVersion"
testImplementation "org.hamcrest:hamcrest-library:$rootProject.ext.hamcrestVersion"
testImplementation "org.mockito:mockito-core:$rootProject.ext.mockitoVersion"
annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.ext.butterknifeVersion"
implementation 'commons-net:commons-net:3.4'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.parse:parse-android:1.15.8'
implementation 'com.parse:parsefacebookutils-v4-android:1.10.4@aar'
implementation 'com.evernote:android-job:1.2.5'
implementation("com.apxor.android:apxor-android-sdk-rta-fcm:1.7.9@aar") {
exclude group: "com.google.firebase"
}
implementation 'me.himanshusoni.chatmessageview:chat-message-view:1.0.7'
implementation 'me.zhanghai.android.materialratingbar:library:1.3.1'
implementation "android.arch.persistence.room:runtime:1.1.1-rc1"
implementation "com.github.vipulasri:timelineview:1.0.6"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1-rc1"

// For appodeal ...
implementation name: 'adcolony-sdk-3.2.1', ext: 'aar'
implementation name: 'mmedia-6.4.0', ext: 'aar'
implementation name: 'mobvista_alphab', ext: 'aar'
implementation name: 'mobvista_appwall', ext: 'aar'
implementation name: 'mobvista_appwallext', ext: 'aar'
implementation name: 'mobvista_common', ext: 'aar'
implementation name: 'mobvista_interstitial', ext: 'aar'
implementation name: 'mobvista_mvdownloads', ext: 'aar'
implementation name: 'mobvista_mvjscommon', ext: 'aar'
implementation name: 'mobvista_mvnative', ext: 'aar'
implementation name: 'mobvista_nativeex', ext: 'aar'
implementation name: 'mobvista_offerwall', ext: 'aar'
implementation name: 'mobvista_playercommon', ext: 'aar'
implementation name: 'mobvista_reward', ext: 'aar'
implementation name: 'mobvista_videocommon', ext: 'aar'
implementation name: 'mobvista_videofeeds', ext: 'aar'

}`

with the following code for repository:
repositories { mavenCentral() jcenter() maven() { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url 'https://maven.fabric.io/public' } // Added for appodeal .. flatDir { dirs 'libs' } }

Not sure what is happening here..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.