Introduction
In this article, we will learn how to create and use extensions for Android development using Kotlin. We have read about Kotlin for Android development. If you are new to Kotlin, read my previous article on Kotlin:
Extensions
Kotlin, similar to C# and Gosu, provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done via special declarations called extensions.
Coding Part
I have detailed the article as in the following steps.
- Step 1 - Creating a new project with Kotlin
- Step 2 - Creating Extensions in Kotlin
- Step 3 - Implementation of Extension in Kotlin
Step 1 - Creating a new project with Kotlin
- Open Android Studio and select "Create new project".
- Name the project as per your wish and tick the Kotlin Support checkbox.
- Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
- Click the "Finish" button to create a new project in Android Studio.
Step 2 - Creating Extensions in Kotlin
In this part, we will see how to create an extension for Kotlin.
- To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended. The following adds a swap function to MutableList<Int>.
- fun MutableList<Int>.swap(index1: Int, index2: Int) {
- val tmp = this[index1]
- this[index1] = this[index2]
- this[index2] = tmp
- }
- We will take an example to show Toast with Short duration. Traditionally, the Toast is shown like below.
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
- We can simplify this by the using extensions in Kotlin.
- Create a Kotlin file named as “Extensions.kt”. Then, add the following code part.
- fun Context.showShortToast(message: CharSequence) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
- }
Here, the base or receiver type of toast is “Context”. So, we have created a function prefixed with “Context”.
- In the same way, I have created an extension to show “Toast with Long duration” and “Alert Dialog with the single option”. You can find the full code below.
- package com.androidmad.ktextensions
-
- import android.content.Context
- import android.support.v7.app.AlertDialog
- import android.support.v7.app.AppCompatActivity
- import android.view.View
- import android.widget.Toast
-
- fun Context.showShortToast(message: CharSequence) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
- }
-
- fun Context.showLongToast(message: CharSequence) {
- Toast.makeText(this, message, Toast.LENGTH_LONG).show()
- }
-
- fun AppCompatActivity.showAlert(title: CharSequence, message: CharSequence) {
- val builder = AlertDialog.Builder(this)
- .setTitle(title)
- .setMessage(message)
- .setPositiveButton("Ok", { dialog, which ->
- })
-
- val dialog: AlertDialog = builder.create()
- dialog.show()
- }
Step 3 - Implementation of Extension in Kotlin
In this section, we will see how to call the above-created extension method in Android.
- Create a layout file named as “activity_main.xml” and add the following code snippets.
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.constraint.ConstraintLayout 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="com.androidmad.ktextensions.MainActivity"
- tools:layout_editor_absoluteY="81dp">
-
- <Button
- android:id="@+id/btn_short"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="128dp"
- android:text="Show Short Toast"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
-
- <Button
- android:id="@+id/btn_long"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="208dp"
- android:text="Show Long Toast"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent" />
-
- <Button
- android:id="@+id/btn_alert"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="92dp"
- android:text="Show Alert Dialog"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent" />
-
- </android.support.constraint.ConstraintLayout>
- The output of the layout file looks like below.
- We have three buttons in our screen to show Toast with Short duration, Long duration and Alert dialog with single option. Open your MainActivity.kt add click listeners for the buttons.
-
- showShortToast("Show Short Toast using extensions method")
-
- showLongToast("Show Long Toast using extensions method")
-
- showAlert("Android Extensions method", "Show Alert Dialog")
- Full code of the MainActivity.kt below..
- package com.androidmad.ktextensions
-
- import android.support.v7.app.AppCompatActivity
- import android.os.Bundle
- import kotlinx.android.synthetic.main.activity_main.*
-
- class MainActivity : AppCompatActivity() {
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
-
- btn_short.setOnClickListener({
- showShortToast("Show Short Toast using extensions method")
- })
-
- btn_long.setOnClickListener({
- showLongToast("Show Long Toast using extensions method")
- })
-
- btn_alert.setOnClickListener({
- showAlert("Android Extensions method", "Show Alert Dialog")
- })
- }
- }
Reference
Download Code
You can download the full source code of the article in
GitHub. If you like this article, do star the repo.