Introduction: In this article, we will learn how to create & use extensions for Android development using Kotlin. We have read abou...

How to use Extensions method in Kotlin How to use Extensions method in Kotlin

How to use Extensions method in Kotlin

How to use Extensions method in Kotlin


Introduction:

In this article, we will learn how to create & 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.

Hello World Android Application Using 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.

  1. Creating New Project with Kotlin
  2. Creating Extensions in Kotlin
  3. Implementation of Extension in Kotlin

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. 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 extensions for Kotlin.

  1. To declare an extensions 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
    fun MutableList<Int>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // 'this' corresponds to the list
        this[index1] = this[index2]
        this[index2] = tmp
    }
  2. 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()
  3. We can simplifies this by the using extensions in Kotlin.
  4. 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”.
  5. In the same way, I have created an extensions to show “Toast with Long duration” and “Alert Dialog with 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 extensions method in android.

  1. 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>
  2. The output of the layout file looks like below
  3. 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.
    // Toast with Short Duration
    showShortToast("Show Short Toast using extensions method")
    // Toast with Long Duration
    showLongToast("Show Long Toast using extensions method")
    // Alert Dialog with Single Option
    showAlert("Android Extensions method", "Show Alert Dialog")
  4. 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:

Extensions in Kotlin https://kotlinlang.org/docs/reference/extensions.html

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

4 comments:

  1. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: blackmart apk free

    ReplyDelete
  2. I gotta favorite this website it seems very helpful . smart glass

    ReplyDelete
  3. By the by these phone are likewise profoundly touchy as they are made of many little sensitive parts, hence it is essentially critical that you take care of your phone well.Iphone reparatur

    ReplyDelete
  4. Great Article. Thank you for sharing! Really an awesome post for every one. There are many companies that specialize in Kotlin app development. CodersNews provide 5 Best Ranked Kotlin Mobile App Development Companies who are proficient in Kotlin and can help businesses develop high-quality apps that meet their specific needs.

    ReplyDelete

Please Comment about the Posts and Blog