info@androidpaper.co.in

How do I create a progress dialog in Kotlin?

In Kotlin, you can create a progress dialog using the ProgressDialog class, which provides a built-in dialog with a spinning wheel or progress bar that indicates an ongoing operation. However, please note that ProgressDialog is now deprecated in API level 26, and it's recommended to use ProgressBar inside a custom dialog or ProgressBar in the layout of your activity/fragment.

Here's how you can create and show a progress dialog using ProgressDialog: Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Learnvibes"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Progress Bar using Kotlin"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
</RelativeLayout>

Step 1: Initialize the ProgressDialog In your activity or fragment, you need to create an instance of ProgressDialog.

import android.app.ProgressDialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MyActivity : AppCompatActivity() {

    private var progressDialog: ProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Your activity setup code here
    }

    // Your other activity methods here
}

Step 2: Show the Progress Dialog To display the progress dialog, call the showProgressDialog() function.

private fun showProgressDialog() {
    progressDialog = ProgressDialog(this)
    progressDialog?.setMessage("Loading...") // Set the message shown in the dialog
    progressDialog?.setCancelable(false) // Set whether the dialog can be canceled by the user
    progressDialog?.show()
}

Step 3: Dismiss the Progress Dialog To dismiss the progress dialog when the operation is complete or when you no longer need it, call the dismissProgressDialog() function.

private fun dismissProgressDialog() {
    progressDialog?.dismiss()
}

You can now use these functions in your activity or fragment to show and dismiss the progress dialog whenever you need it.