An example for who are all going to start learning Kotlin programming language to develop Android application.

Overview

Kotlin Example

Here is an example for who are all going to start learning Kotlin programming language to develop Android application.

First check this example APK to understand basic steps easily. I enjoyed a lot while doing this tutorial, If your Java developer you can play with this. Happy Coding!

Get it on Google Play

Kotlin is very lightweight, its run-time library is under 400K minus the ProGuard minification. Also, installation is very simple. All you have to do is browse the plugin repository and get the official Kotlin plugin. You also had to install Kotlin Android Extensions as well, required for Android of course, but not until recently it has been merged with the Kotlin plugin and is now obsolete.

Settings > Plugins > Browse Repositories > Search Kotlin and install

To configure Kotlin in your project, convert any source file to Kotlin first.

Select a Java file > Hit Ctrl+Shift+A > “convert to kotlin” Hit enter

Take a look here for screenshots and brief explanation.

Android UI With Anko

Anko is a library made in Kotlin that is a great utility for Android development. It consists of DSL wrappers and other nice extensions that make development easier. The prime value of Anko is that it allows you to embed UI layouts inside your source code, which makes it type-safe and allows programmatic transformation.

Just a brief example. Here is a "hello world" written with Anko:

verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

Started by letting Gradle know some dependencies, one set for the Support Library, another for the Kotlin run-time, and one more set for Anko obviously.

Reference those dependencies
final SUPPORT_VERSION = '23.3.0'
final ANKO_VERSION = '0.8.3'

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile "com.android.support:appcompat-v7:${SUPPORT_VERSION}"
    compile "com.android.support:recyclerview-v7:${SUPPORT_VERSION}"
    compile "org.jetbrains.anko:anko-sdk15:${ANKO_VERSION}"
    compile "org.jetbrains.anko:anko-appcompat-v7:${ANKO_VERSION}"
    compile "org.jetbrains.anko:anko-recyclerview-v7:${ANKO_VERSION}"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

One thing to be noted here, the Anko base library, i.e., the anko-sdk* lib, you should add on the basis of your minimum SDK version and the rest of the other dependencies, you add on the basis of the Support Library that you wish to extend with Anko. For instance, add anko-design for design, which is from the Support Library.

Example

Kotlin Example - Splashscreen Kotlin Example - MainScreen Kotlin Example - Menu Kotlin Example - WebView

SplashScreenActivity.kt

Splash screen is one of the friend for android developers will see most of the times this screen while developing interesting concepts. Here you can see how Splashscreen code looks interms of Kotlin.

Note: Here i followed this tutorial to create express splashscreen.

class : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Start main activity
        startActivity(Intent(this, MainActivity::class.java))

        // close this activity
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out)
        finish()
    }

}
Some Awesome methods/functions
Variable declaration. int/string/boolean
var EMAIL_ID = "[email protected]"
To open Web URL
browse(GIT_HUB_URL)
setText function
tvHeader.text = HEADER_TEXT
Hint to Edit Text
etName.hint = EDIT_TEXT_NAME_HINT
Toast
toast("Activity restarted!")
Email Intent
email(EMAIL_ID, "subject")
Share Intent
share("text")
Function declaration, function to get text length of edit text
fun checkTextLength(editText: EditText): Boolean {
        var length = editText.length()
        if (length > 0)
            return true
        else
            return false
}
onClick funtion
btDone.onClick {
            hideKeyboard()
            if (!checkTextLength(etName) || !checkTextLength(etMobile))
                toast("Fields cannot be empty!")
            else
                onButtonClicks()
}
Dialog Aleart Box
fun openAlertDialog(name: String, phoneNumber: String) {

        val countries = listOf("Russia", "India", "USA", "Japan", "China")

        selector("Where are you from?", countries) { i ->
            alert("One more thing! You have entered this number " + phoneNumber, name + "! So you're living in ${countries[i]}, right?")            {
                customView {
                    verticalLayout {
                        positiveButton("AWESOME!") {
                            longToast("Thank you!")
                        }
                    }
                }

            }.show()
}
Initializing menu options
 override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        getMenuInflater().inflate(R.menu.menu_main, menu)
        return true
    }

 override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        val id = item!!.getItemId()
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_rate) {
            // opining browser intent
            browse(PLAY_STORE_URL)
            return true
        }
        return super.onOptionsItemSelected(item)
    }

MainActivity.kt

Main screen, The wall where Android developer paint and repair. Here you can observe the code how plain and simple. Basically i started loving Kotlin while writing this class.

Note: I used Google Custom Tabs library to understand how third party java libraries will work with Kotlin.

class MainActivity : AppCompatActivity() {

    var HEADER_TEXT = "You can try awesome example!"
    var EDIT_TEXT_NAME_HINT = "enter name"
    var EDIT_TEXT_NUMBER_HINT = "enter number"
    var EMAIL_ID = "[email protected]"
    var GIT_HUB_URL = "https://github.com/myinnos/Kotlin-Example"
    var GIT_HUB_WEB_URL = "https://myinnos.github.io/Kotlin-Example/";
    var PLAY_STORE_URL = "market://details?id=" + BuildConfig.APPLICATION_ID

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

        // setting header text
        tvHeader.text = HEADER_TEXT
        // setting hint for edit text
        etName.hint = EDIT_TEXT_NAME_HINT
        etMobile.hint = EDIT_TEXT_NUMBER_HINT

        // setting drawable image to image view
        imageView.resources.getDrawable(R.mipmap.ic_launcher)

        // onclick event for image view to restart activity (Intent function)
        imageView.onClick {
            startActivity<SplashScreenActivity>()
            finish()
            toast("Activity restarted!")
        }

        // onclick event for button
        btDone.onClick {
            hideKeyboard()
            if (!checkTextLength(etName) || !checkTextLength(etMobile))
                toast("Fields cannot be empty!")
            else
                onButtonClicks()
        }

        btGitHubLink.onClick {
            // opining browser intent
            browse(GIT_HUB_URL)
        }

        btTutorial.onClick {
            // google custom tabs
            val builder = CustomTabsIntent.Builder()
            builder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary))
            val customTabsIntent = builder.build()
            customTabsIntent.launchUrl(this, Uri.parse(GIT_HUB_WEB_URL))
        }
    }

    // function to get text from edit text
    fun EditText.textValue(): String {
        return text.toString()
    }

    // function to get text length of edit text
    fun checkTextLength(editText: EditText): Boolean {

        var length = editText.length()

        if (length > 0)
            return true
        else
            return false
    }

    // function to hide keyboard
    fun hideKeyboard() {
        try {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        } catch (e: Exception) {
            // TODO: handle exception
        }

    }

    fun onButtonClicks() {
        //using function
        val phoneNumber = etMobile.textValue()
        // direct access
        val name = etName.text.toString()
        // calling alert dialog
        openAlertDialog(name, phoneNumber)
    }

    fun openAlertDialog(name: String, phoneNumber: String) {

        val countries = listOf("Russia", "India", "USA", "Japan", "China")

        selector("Where are you from?", countries) { i ->
            //toast("So you're living in ${countries[i]}, right?")
            alert("One more thing! You have entered this number " + phoneNumber, name + "! So you're living in ${countries[i]}, right?") {
                customView {
                    verticalLayout {
                        positiveButton("AWESOME!") {
                            longToast("Thank you!")
                        }
                    }
                }

            }.show()

        }
    }

    // Initializing menu options
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item!!.getItemId()

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_share) {
            // sharing intent
            share(getString(R.string.share_text) + BuildConfig.APPLICATION_ID,
                    getString(R.string.app_name))
            return true
        } else if (id == R.id.action_feedback) {
            // email intent
            email(EMAIL_ID, getString(R.string.app_name))
            return true
        } else if (id == R.id.action_rate) {
            // opining browser intent
            browse(PLAY_STORE_URL)
            return true
        }

        return super.onOptionsItemSelected(item)
    }
}

Conclusion

Kotlin is overall a great language. It is much less verbose than Java, and has an excellent standard library that removes the need to use a lot of the libraries that make Java life bearable. Converting an app from Java to Kotlin is made much easier thanks to automated syntax conversion, and the result is almost always an improvement. If you’re an Android developer, you owe it to yourself to give it a try.

Any Queries? or Feedback, please let me know by opening a new issue!

Contact

Prabhakar Thota

License

Copyright 2017 MyInnos

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
Android Ptrace Inject for all ABIs and all APIs. Help you inject Shared Library on Android.

Android Ptrace Inject 中文可以参考我的注释内容进行理解 我写的注释相对来说比较全面了 How to build Make sure you have CMake and Ninja in your PATH Edit CMakeLists.txt. Set ANDROID_ND

A pair of applications provide a direct means of integrating with one another via application programming interfaces (APIs)

What is a native integration? It's when a pair of applications provide a direct means of integrating with one another via application programming interfaces (APIs). Once integrated, data can flow between the apps and become more readily available to your employees.

An android application for generating random quotes for learning Room, Jetpack Navigation and Lifecycles, Retrofit
An android application for generating random quotes for learning Room, Jetpack Navigation and Lifecycles, Retrofit

Random-Quote-Generator An android application for generating random quotes for learning Room, Jetpack Navigation and Lifecycles, Retrofit MAD Score Te

ATH Sample is a sample Authentication and Authorization Application with Kotlin Language and MVVM architecture.
ATH Sample is a sample Authentication and Authorization Application with Kotlin Language and MVVM architecture.

ATH Sample ATH Sample is a sample Authentication and Authorization Application with Kotlin Language and MVVM architecture. Overview ATH Sample is a sa

Android utilities for easier and faster Kotlin programming.
Android utilities for easier and faster Kotlin programming.

Android utilities for easier and faster Kotlin programming. Download Gradle compile 'com.costular:kotlin-utils:0.1' How to use It depends on utilities

A template that utilizes both Scala and Kotlin because why not (And also because I endorse programming hell)

Fabric-Scala-Kotlin-template A template that utilizes both Scala and Kotlin because why not (And also because I endorse programming hell) I don't care

Playground for learning Kotlin Multiplatform Mobile
Playground for learning Kotlin Multiplatform Mobile

This is a playground for learning KMP (KMM Plugin for android studio). Requirements Android Studio Canary 8 Architecture Thanks https://twitter.com/jo

Learning Playground - Kotlin Coroutines

Coroutines Kotlin Playground Coroutines Learning Playground Colaborator Very ope

Clean Code and Reactive Programming PlayGround for Bangkit 2021

Clean Code and Reactive Programming PlayGround for Bangkit 2021 Hello! This repo contains the IntelliJ project that I use to present my talk, "Clean A

Comments
  • [ImgBot] optimizes images

    [ImgBot] optimizes images

    Beep boop. Your images are optimized!

    Your image file size has been reduced by 38% 🎉

    Details

    | File | Before | After | Percent reduction | |:--|:--|:--|:--| | /icons/playstore/icon.png | 28.31kb | 14.93kb | 47.26% | | /icons/mipmap-xhdpi/ic_launcher.png | 3.70kb | 2.37kb | 35.97% | | /app/src/main/res/mipmap-xhdpi/ic_launcher.png | 3.70kb | 2.37kb | 35.97% | | /icons/mipmap-xxxhdpi/ic_launcher.png | 7.97kb | 5.18kb | 35.10% | | /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png | 7.97kb | 5.18kb | 35.10% | | /app/src/main/res/mipmap-xxhdpi/ic_launcher.png | 5.92kb | 4.03kb | 31.96% | | /icons/mipmap-xxhdpi/ic_launcher.png | 5.92kb | 4.03kb | 31.96% | | /icons/mipmap-hdpi/ic_launcher.png | 2.87kb | 2.13kb | 25.95% | | /app/src/main/res/mipmap-hdpi/ic_launcher.png | 2.87kb | 2.13kb | 25.95% | | /icons/mipmap-mdpi/ic_launcher.png | 1.82kb | 1.39kb | 23.78% | | /app/src/main/res/mipmap-mdpi/ic_launcher.png | 1.82kb | 1.39kb | 23.78% | | | | | | | Total : | 72.88kb | 45.10kb | 38.12% |


    📝docs | :octocat: repo | 🙋issues | 🏅swag | 🏪marketplace

    opened by imgbot[bot] 0
  • This line doesnt set the drawable

    This line doesnt set the drawable

    https://github.com/myinnos/Kotlin-Example/blob/d13091fabbbf3b85b2df91ae91a1c62194784264/app/src/main/java/in/myinnos/kotlinexample/MainActivity.kt#L38

    opened by doug-samuel 0
Owner
Prabhakar Thota
Mobile Engineer[AIML], UI/UX. I believe in the quote which says "Creativity is thinking up new things. Innovation is doing new things." Happy Coding :)
Prabhakar Thota
Exercises for Functional Programming learning in Kotlin with Arrow

Exercises for Functional Programming in Kotlin with Arrow-kt Exercises and practice code for Functional Programming learning in Kotlin with Arrow Requ

Jack Lo 3 Nov 11, 2021
Ivy FRP is a Functional Reactive Programming framework for declarative-style programming for Android

FRP (Functional Reactive Programming) framework for declarative-style programming for Andorid. :rocket: (compatible with Jetpack Compose)

null 8 Nov 24, 2022
Concurrency-programming - Homework for the course of Concurrency Programming, ITMO CT, Autumn 2020

Homework for the course of Concurrency Programming, ITMO CT, Autumn 2020 Выполни

Grigoriy Khlytin 2 Jan 23, 2022
Lambda-snake.kt - Snake Game Implementation for Web using Kotlin programming language compiled for Javascript

Projeto da disciplina de Linguagem de Programação Funcional 2021.1 (jan/2022) ??

Alex Candido 3 Jan 10, 2022
An under development minecraft plugin (1.8.8) to learning Kotlin language

CorePlus CorePlus is a minecraft plugin coded with Kotlin language. Still under development CorePlus will be an essential for each minecraft servers !

Gonz 3 Jun 16, 2021
A sample project that helps to start building a Mobile Kotlin Multiplatform application

Mobile Kotlin multiplatform project template A sample project that helps to start building a Mobile Kotlin Multiplatform application. It establishes a

Dizel 0 Oct 16, 2021
Android MVVM framework write in kotlin, develop Android has never been so fun.

KBinding 中文版 Android MVVM framework write in kotlin, base on anko, simple but powerful. It depends on my another project AutoAdapter(A library for sim

Benny 413 Dec 5, 2022
Develop an API that moves a rover around on a grid

Mars Rover Kata Develop an API that moves a rover around on a grid. Rules: You are given the initial starting 2D point (x,y) of a rover and the direct

Alvaro Martin Rodriguez 1 Dec 17, 2021
Simple Android Library, that provides easy way to start the Activities with arguments.

Warning: Library is not maintained anymore. If you want to take care of this library, propose it via Pull Request. It needs adjustmensts for newer ver

Marcin Moskała 429 Dec 15, 2022
Example of migrating from Dagger to Hilt with a real service/repository example

DaggerToHilt Overview This repo provides a real example of using Hilt for dependency injection. It hits endpoints provided by the Movie Database, and

null 0 Nov 29, 2021