Button Clicked After 10 second Kotlin Tutorial with Code

Admin
0


To implement a button that, when clicked, waits for 10 seconds before performing an action in an Android app, you can use a Handler or Coroutine to delay the action. Here's how to do it using both approaches.

1. Using Handler

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

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

        val myButton: Button = findViewById(R.id.my_button)

        myButton.setOnClickListener {
            // Wait for 10 seconds (10,000 milliseconds)
            Handler(Looper.getMainLooper()).postDelayed({
                // Action to perform after 10 seconds
                Toast.makeText(this, "Action performed after 10 seconds!", Toast.LENGTH_SHORT).show()
            }, 10000) // 10 seconds delay
        }
    }
}

2. Using Kotlin Coroutines

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

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

        val myButton: Button = findViewById(R.id.my_button)

        myButton.setOnClickListener {
            CoroutineScope(Dispatchers.Main).launch {
                delay(10000) // 10 seconds delay
                // Action to perform after 10 seconds
                Toast.makeText(this@MainActivity, "Action performed after 10 seconds!", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Explanation:

Handler (1st method): It uses Handler with a delay to post a task to the main thread after a specified delay.

Coroutines (2nd method): This uses Kotlin coroutines for asynchronous programming. It pauses the execution for 10 seconds using delay() and then performs the action.

Both approaches will trigger the action 10 seconds after the button is clicked.


Tags

Post a Comment

0 Comments
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Ok, Go it!