Friday, August 14, 2020

android kotlin - Do a task after a delay

MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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


        // start a 5 seconds delayed task using handler
        Handler(Looper.getMainLooper()).postDelayed({
                textView.text = "Text changed after 5 seconds delay."
            },5000)



        // initialize an instance of handler
        val handler = Handler(Looper.getMainLooper())

        // delayed task on button click
        button.setOnClickListener {
            val runnable = Runnable { // do some task on delay
                // set the text view  text color to red
                textView.setTextColor(Color.RED)
            }

            // schedule a 4 seconds delayed task
            handler.postDelayed(runnable, 4000)
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E5E4E2"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Task After Delay"
        android:backgroundTint="#5946B2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:text="TextView"
        android:textColor="#191970"
        android:textSize="33sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>