Country Code Picker with Kotlin

Country code pickers are used to search and select country code or international phone code in android. This example describes how to add a country code picker using Kotlin for Android application .

  • First we needed to add the following dependency into our applications app level build.gradle file.

implementation ‘com.hbb20:ccp:2.2.2’

  • Add the following code into your activity_main.xml file 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.hbb20.CountryCodePicker
        app:ccp_hintExampleNumber="true"
        android:id="@+id/country_code_picker"
        android:clickable="true"
        android:focusable="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </com.hbb20.CountryCodePicker>

</RelativeLayout>

To hide flag
app:ccp_showFlag=”false”

To hide Name code
app:ccp_showNameCode=”false”

  • In your MainActivity.kt
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.hbb20.CCPCountry
import com.hbb20.CountryCodePicker

class MainActivity : AppCompatActivity() ,CountryCodePicker.OnCountryChangeListener{
    private var ccp:CountryCodePicker?=null
    private var countryCode:String?=null
    private var countryName:String?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

         ccp = findViewById(R.id.country_code_picker)
        ccp!!.setOnCountryChangeListener(this)

        //to set default country code as Japan
        
        ccp!!.setDefaultCountryUsingNameCode("JP")
    }

    override fun onCountrySelected() {
        countryCode=ccp!!.selectedCountryCode
        countryName=ccp!!.selectedCountryName

        Toast.makeText(this,"Country Code "+countryCode,Toast.LENGTH_SHORT).show()
        Toast.makeText(this,"Country Name "+countryName,Toast.LENGTH_SHORT).show()
    }

}

That’s it! Now run the project!

Thanks for reading!