ViewPager In Kotlin Android

Here we provides a simple tutorials to implement ViewPager in Kotlin.

ViewPager is one of most popular widgets available in android libraries. It is used in most of the famous apps like PlayStore,WhatsApp etc.

ViewPager is a widget that is used to implement tabs in Android Applications. ViewPager allows users to swipe left or right to see new screens.

Setup Layout file

This step is to add ViewPager in your Layout file. Go to your xml file and add the following code into it.

Make sure you have added the following dependency in your build.gradle file

implementation ‘com.android.support:design:27.1.1’

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabGravity="fill"
        app:tabMode="fixed" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#c6c4c4" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Implementing The Activity

Now we will implement the MainActivity.kt. Please keep in mind.

  • MainActivity class have a Fragment and FragmentPagerAdapter to setup the view pager, this are defined bit later
  • FragmentPagerAdapter inherited from PagerAdapter
  • Function initViews()  initializes the views
  • Function setupViewPager()  setting up the ViewPager 

MainActivity.ktI

package kotlincodes.com.viewpagerkotlin.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import kotlincodes.com.viewpagerkotlin.R
import kotlincodes.com.viewpagerkotlin.ViewPagerAdapter.MyFragmentPagerAdapter
import kotlincodes.com.viewpagerkotlin.fragments.MyFrament

class MainActivity : AppCompatActivity() {

    private lateinit var viewpager: ViewPager
    private lateinit var tabs: TabLayout

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

        initViews()

        setupViewPager()
    }

    private fun initViews() {
        tabs = findViewById(R.id.tabs)
        viewpager = findViewById(R.id.viewpager)
    }

    private fun setupViewPager() {

        val adapter = MyFragmentPagerAdapter(getSupportFragmentManager())

        var firstFragmet: MyFrament = MyFrament.newInstance("First Fragment")
        var secondFragmet: MyFrament = MyFrament.newInstance("Second Fragment")
        var thirdFragmet: MyFrament = MyFrament.newInstance("Third Fragment")

        adapter.addFragment(firstFragmet, "ONE")
        adapter.addFragment(secondFragmet, "TWO")
        adapter.addFragment(thirdFragmet, "THREE")

        viewpager!!.adapter = adapter

        tabs!!.setupWithViewPager(viewpager)

    }
}

Implementing The PagerAdapter Class

Now that we have the MainActivity.kt covered, we need to define the FragmentPagerAdapter Class. We have a addFragment inside FragmentPagerAdapter to add the Fragments .

MyFragmentPagerAdapter.kt

package kotlincodes.com.viewpagerkotlin.ViewPagerAdapter

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import java.nio.file.Files.size
import android.support.v4.app.FragmentPagerAdapter
import kotlincodes.com.viewpagerkotlin.fragments.MyFrament


class MyFragmentPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
    private val mFragmentList: ArrayList<Fragment> = ArrayList()
    private val mFragmentTitleList: ArrayList<String> = ArrayList()

    override fun getItem(position: Int): Fragment {
        return mFragmentList.get(position)
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList.get(position)
    }
}

Setting Up The Fragment

We are almost finished now we need to setup the Fragmet class. First we need to set the fragment_home.xml layout

Layout have only a TextView to indicate the changes .

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:padding="12dp"
        android:background="#000"
        android:id="@+id/text"
        android:layout_centerInParent="true"
        android:textSize="22dp"
        android:textAllCaps="true"
        android:text="Fragment ONE"
        android:textAlignment="center"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

now we need to setup the Fragment class MyFragment.kt

package kotlincodes.com.viewpagerkotlin.fragments

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.TextureView
import android.widget.TextView
import kotlincodes.com.viewpagerkotlin.R
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.provider.AlarmClock.EXTRA_MESSAGE


class MyFrament : Fragment() {
    companion object {
        fun newInstance(message: String): MyFrament {

            val f = MyFrament()

            val bdl = Bundle(1)

            bdl.putString(EXTRA_MESSAGE, message)

            f.setArguments(bdl)

            return f

        }
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view: View? = inflater.inflate(R.layout.fragment_home, container, false);

        val message = arguments!!.getString(EXTRA_MESSAGE)

        var textView: TextView = view!!.findViewById(R.id.text)
        textView!!.text = message

        return view
    }


}

That’s With the above we can simply implement a  ViewPager in Kotlin. you can also get a Source code of the project from GitHub


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!


Get Started with Kotlin in Android studio

Kotlin is fully supported with android studio v3.0 and Higher.

  • Setup Kotlin to Android Studio

Important : The android studio version must be 3.0 or higher

To add Kotlin support to the android studio we need to install the Kotlin plugin for your Android Studio.

To add the Kotlin plugin open

Android Studio File → Settings  → Plugins →type “Kotlin” in search box → Click Browse in Repositories → install →  Restart Android studio to activate the Plugin

 

Add Kotlin to the existing project

Add classpath in project level build.gradle.

Also here defined a variable kotlin_version as ext.kotlin_version = ‘1.2.41’ to share the version to all.

<// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {
        ext.kotlin_version = '1.2.41'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

2. Add dependencies to app level build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

dependencies {

implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

} 

 

Create a new project with Kotlin

Open android studio then click File –> New project you will get a window like below

Mark Include Kotlin Support 

Press Next–>Opens a page to select minimum SDK version — select API v15

Press Next –>Opens a page to select the default activity type — Choose Empty Activity from the list

Press Next –> Opens a page to change the default activity name

Press Finish — >Opens A new Android Project with Kotlin Support.


Kotlin : A new era in android app development

  • Introduction

Since long we have known and uses Java as the primary language for android app development. But recently a comparatively new language called Kotlin is taking over java in android development , A lot of developers now chooses Kotlin in their new android projects instead of Java.

  • What is Kotlin

Kotlin is a general purpose, open source, statically typed programming language for modern multi-platform applications. Kotlin combines object-oriented and functional programming features.  It is mainly focused on interoperability, safety, clarity, and tooling support.

Kotlin is developed by JetBrains,the company behind IntelliJ IDEA ,in 2010 and has been open source since 2012.

  • History

In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which had been under development for a year. Development lead by Andrey Breslav stated that Kotlin is   “better language” than Java, but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin.One of the main goals was to compile as quickly as java

In February 2012 JetBrains open sourced the project under the Apache 2 licence.

Officially stable release Kotlin v1.0 was released on February 15 ,2016.

In 2017 annual developer conference held by google ( Google I/O  ) announced first-class support for Kotlin on Android.

Kotlin v1.2 was released on November 28, 2017. Sharing code between JVM and Javascript platforms feature was newly added to this release

The name comes from Kotlin Island, near St. Petersburg Russia .

  • Java or Kotlin for Android development

In case of android app development Java is most favourite language of many developers .But did you know that kotlin is ready to challenge Java’s leadership in the Android application development and a lot of developers are switching from java to kotlin.

Let’s have a detailed comparison of java and Kotlin.

  1. Java

In case of android development Java is mostly used and favourite of many developers also Android itself is written in Java. Java is a object oriented programming language that holds the cap of second most active programming language ion Github. And probably one of the oldest programing language around 20 years of active.

Pros of Java

  • Simple : Java is easy to learn,use,write,compile and debug than alternative programming languages.
  • Compilation speed is high
  • In case of cross platform applications Java is a far better choice .
  • Most of the android applications are running on Java and A lot of java libraries are available for android SDK
  • Java has a large open-source ecosystem, partly as a result of Google’s adoption of the Java Virtual Machine (JVM) for Android;
  • In comparison to Kotlin  Java applications are more compact and lighter
  • The build & compilation speed is high than Kotlin  
  • Lot of tutorials and online materials are available  for android development using java ,In case of Kotlin as its a new language the materials are limited.

Cons of Java

  1. Java has limitations that cause problems with Android API design
  2. As compare with Kotlin , More code is needed to be written in java .
  3. It is slower and more memory consuming .than many other language

Kotlin

Kotlin was designed by programmers from JetBrains to add some modern features to Java that come in handy in mobile development. Kotlin is an open source, statically typed language based on Java Virtual Machine (JVM), but you can also compile it to JavaScript or Native for building code that can run on iOS. All it takes is installing the Kotlin Plugin and letting it configure your project.

Pros of Kotlin

  • Fully compatible and easy to convert from java to Kotlin : Just install Kotlin plugin in Android SDK and sync gradle then click Convert to convert java files to Kotlin
  • All major java frameworks started supporting Kotlin (Like Spring started support Kotlin from Spring 5)
  • Well management in NullPointerException : Introduction of !! operator aimed to eliminate NullPointerException’s the  code.
  • Fewer chance to get errors in code and in compare to java less coding needed.
  • Easy to switch from Java to Kotlin
  • All java libraries are fully compatible with Kotlin
  • Compilation time in kotlin are improving well and almost same as that of Java.

Cons of Kotlin

  • Slower compilation speed than Java
  • Switching entire team from Java to Kotlin might be challenging
  • The availability of developer community and finding answers for questions are limited , but its growing fastly.
  • In android studio auto_completion are working slower than Java.

Kotlin version history

  • Kotlin v1.0 : Official stable version of Kotlin released on February 15 ,2016.
  • Kotlin v1.2 : Added the possibility to reuse code between the JVM and JavaScript,new libraries introduced to help cross platform applications
  • Kotlin v1.2.2 :Adds support for Gradle build cache
  • Kotlin v1.2.6 : latest version available and released on Aug 1, 2018.
  • Kotlin v1.2.3 : Adds a new declaration in the standard library, which imitates the suspend
  • Kotlin v1.3 : upcoming version
  • Conclusion

In my opinion If you are a beginner in android development and you have a decent knowledge in Java , its better to start with Kotlin instead of Java. But of course you might have some  good knowledge in Java.

Kotlin is now an Official language for android development and a lot of brands like Amazon,pintrest and netflix are already converted to kotlin.  As the article name says it is a new era in android development and Kotlin is only beginning to ride in the growth curve. With support from Google and heavy-hitting brands making the switch kotlin quickly proving itself to be a superior programming language for android application development.

Some Useful tutorials

Java or Kotlin for Android development

In case of android app development Java is most favourite language of many developers .But did you know that kotlin is ready to challenge Java’s leadership in the Android application development and a lot of developers are switching from java to kotlin.

Let’s have a detailed comparison of java and Kotlin.

 


  • Java

In case of android development Java is mostly used and favourite of many developers also Android itself is written in Java. Java is a object oriented programming language that holds the cap of second most active programming language ion Github. And probably one of the oldest programing language around 20 years of active.

Pros of Java

  • Simple : Java is easy to learn,use,write,compile and debug than alternative programming languages.
  • Compilation speed is high
  • In case of cross platform applications Java is a far better choice .
  • Most of the android applications are running on Java and A lot of java libraries are available for android SDK
  • Java has a large open-source ecosystem, partly as a result of Google’s adoption of the Java Virtual Machine (JVM) for Android;
  • In comparison to Kotlin  Java applications are more compact and lighter
  • The build & compilation speed is high than Kotlin  
  • Lot of tutorials and online materials are available  for android development using java ,In case of Kotlin as its a new language the materials are limited.

Cons of Java

  • Java has limitations that cause problems with Android API design
  • As compare with Kotlin , More code is needed to be written in java .
  • It is slower and more memory consuming .than many other languages

 

 


  • Kotlin

Kotlin was designed by programmers from JetBrains to add some modern features to Java that come in handy in mobile development. Kotlin is an open source, statically typed language based on Java Virtual Machine (JVM), but you can also compile it to JavaScript or Native for building code that can run on iOS. All it takes is installing the Kotlin Plugin and letting it configure your project.

Pros of Kotlin

  • Fully compatible and easy to convert from java to Kotlin : Just install Kotlin plugin in Android SDK and sync gradle then click Convert to convert java files to Kotlin
  • All major java frameworks started supporting Kotlin (Like Spring started support Kotlin from Spring 5)
  • Well management in NullPointerException : Introduction of !! operator aimed to eliminate NullPointerException’s the  code.
  • Fewer chance to get errors in code and in compare to java less coding needed.
  • Easy to switch from Java to Kotlin
  • All java libraries are fully compatible with Kotlin
  • Compilation time in kotlin are improving well and almost same as that of Java.

Cons of Kotlin

  • Slower compilation speed than Java
  • Switching entire team from Java to Kotlin might be challenging
  • The availability of developer community and finding answers for questions are limited , but its growing fastly.
  • In android studio auto_completion are working slower than Java.

 

  • Conclusion

 

In my opinion If you are a beginner in android development and you have a decent knowledge in Java , its better to start with Kotlin instead of Java. But of course you might have some  good knowledge in Java.

Kotlin is now an Official language for android development and a lot of brands like Amazon,pintrest and netflix are already converted to kotlin.  As the article name says it is a new era in android development and Kotlin is only beginning to ride in the growth curve. With support from Google and heavy-hitting brands making the switch kotlin quickly proving itself to be a superior programming language for android application development.