Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


Twitter


Create a loading screen with Kotlin in Android Studio

Bart SimonsBart Simons

untitled

Want to your app loading screen to look like this? Making your app look beautiful is very important, you want to give your users the best you can give at moments when they can get impatient. I have tried out Lottie last week, and it made my loading screen look just so much better in comparison with a boring static loading screen. In this guide I am going to show you step-by-step what it takes to create a beautiful loading screen for your app.

The beginning

I am going to start off by creating a new Android Studio project with Kotlin support:

create-android-project-kotlin

Please note that Lottie - one of the dependencies needed for this project - requires at least API level 16 (also known as Android Jellybean or Android 4.1).

Update your gradle build script so that it includes Lottie as a dependency:

build-gradle-script-lottie

Press the 'Sync Now' label/button to synchronize all the needed files for your project. This process is very intensive on your computer's resources so take a quick coffee break (or a tea break if that is your thing) while your computer is busy crushing numbers!

jim-carrey-coffee

So, what now? After your computer is done syncing your dependencies you should decide on what activity you want your loading screen to appear on. I just want to display a loading screen on my first (startup) activity, so I will use this activity in this guide.

Get started by creating a new file called LoadingAsync.kt:

create-kotlin-class

create-kotlin-class-2

Put this code in your LoadingAsync.kt:

package me.bartsimons.mytestapp

import android.os.AsyncTask

interface LoadingImplementation {
    fun onFinishedLoading()
}

class LoadingAsync(private val listener: LoadingImplementation) : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void?): Void {
        for (i in 0 until 10) {
            Thread.sleep(1000)
        }
    }

    override fun onPostExecute(result: Void?) {
        super.onPostExecute(result)

        listener.onFinishedLoading()
    }
}

This might seem very complex, but it actually is not: this is just a class that implements an AsyncTask, together with an interface that we can use to properly run UI code after all loading is finished. I have used a for loop that sleeps for one second during each iteration - this is to simulate code that takes a long time to finish.

PS: Do not forget to replace the package name with your own package name!

Getting a nice loading animation

There's a website called https://www.lottiefiles.com which you should check out. They have a huge collection of animation files that you can use for your app. After you have downloaded an animation, make sure if the download is zipped or not. If it's just a json file that you have downloaded, you're good to go. If it's zipped, you should extract the json file to somewhere else first.

Go back to Android Studio, right click on the app folder and click on 'Show in explorer'. If you use a Mac, it might be called 'Show in finder'.

show-explorer-app

Navigate to app/src/main in your explorer or finder window and create a folder called assets. Now, drop your animation .json file right there. I called mine loading.json.

Writing the animation code

Create a Kotlin class like we did before, and call it LoadingAnimation. Put the following code in it:

package me.bartsimons.mytestapp

import android.app.Activity
import android.widget.RelativeLayout
import com.airbnb.lottie.LottieAnimationView

class LoadingAnimation constructor(private val context: Activity, animationName: String) {
    private var lottieAnimationView : LottieAnimationView = LottieAnimationView(context)

    private var rLayout : RelativeLayout = RelativeLayout(context)
    private var rLayoutParams : RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT)

    private val lLayoutParams : RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)

    init {
        lottieAnimationView.setAnimation(animationName)
        lottieAnimationView.layoutParams = lLayoutParams

        rLayout.addView(lottieAnimationView)
    }

    fun playAnimation(loop: Boolean) {
        lottieAnimationView.loop(loop)
        context.setContentView(rLayout, rLayoutParams)
        lottieAnimationView.playAnimation()
    }

    fun stopAnimation(originalView: Int) {
        lottieAnimationView.cancelAnimation()
        context.setContentView(originalView)
    }
}

Great! If you are very eager to test it out, go ahead and use this code snippet to test it out:

val loadingAnimation = LoadingAnimation(this, "loading.json")
loadingAnimation.playAnimation(true)

Please note that the first argument in the LoadingAnimation constructor should be an Activity object (although, objects like AppCompatActivity do work too).

This should play the animation on your screen. You can stop it with

loadingAnimation.stopAnimation(R.layout.activity_main)

With R.layout.activity_main I am referring to my original content view.

Implementing LoadingAsync in our activity

To implement LoadingAsync in our activity, we need to 'implement' the class like this:

# Before:
class MainActivity : AppCompatActivity() {

# After:
class MainActivity : AppCompatActivity(), LoadingImplementation {

This should give you a new error, and that's no problem. To fix this, you need to define a method called onFinishedLoading:

override fun onFinishedLoading() {
    # After loading is done, stop the animation and reset the current view
    loadingAnimation.stopAnimation(R.layout.activity_main)
}

My full MainActivity code looks like this:

package me.bartsimons.mytestapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity(), LoadingImplementation {
    override fun onFinishedLoading() {
        loadingAnimation.stopAnimation(R.layout.activity_main)
    }

    private lateinit var loadingAnimation : LoadingAnimation

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

        loadingAnimation = LoadingAnimation(this, "loading.json")

        loadingAnimation.playAnimation(true)
        LoadingAsync(this).execute()
    }
}

The code above is pretty much self-explanatory. This should show the loading screen for 10 seconds, and after that it shows the original view after 'loading' is done.

That's it! If you like my content and/or if my content helped you out, please share it with fellow tech enthousiasts or share it on social media, thank you for that. Have a nice day!

Bart Simons
Author

Bart Simons

Comments