Zero Float
Zero Float

Reputation: 1

Using Array elements with delay in kotlin /Android Studio

I'm trying to pass each element in an array with delaying between them in a TextView I tried using Runnable & Handler but it only shows the last one how can I pass each one separately with 5-sec delaytion......

class MainActivity : AppCompatActivity() {

    var array = arrayListOf("bizza","Dolma","Burger","Salut","Drinks","Sussie")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         var ran = Runnable {
            firsttxtview.setText((array[0]).toString())
         }
         var hand = Handler()
         hand.postDelayed(ran, 3000)
}

Upvotes: 0

Views: 313

Answers (3)

Animesh Sahu
Animesh Sahu

Reputation: 8106

Every android.os.Handler has its own thread associated with it. A thread is an expensive resource. In better programming techniques you should never create new threads for very small operations.

Android already comes with a Dispatchers.Main CoroutineDispatcher which runs on UI thread forever.

You can use it to launch the coroutine into the ui thread directly:

class MainActivity : AppCompatActivity() {

    private var job = Job()
    private var scope = CoroutineScope(Disptachers.Main + job)
    ...

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        if(!job.isActive) {
            job = Job()
            scope += job
        }
        ...
        val viewChangeJob = scope.launch { // can omit creating variable if you don't need
            delay(3_000)
            firsttxtview.setText(array[0])

            // or change text every 3 sec taking every element of array
            // for(item in array) {
            //     delay(3_000)
            //     firsttxtview.setText(item)
            // }
        }

    }

    override fun onDestroy() {
        job.cancel()
    }

Here you also have full control over the jobs, you can cancel them or pause them etc. It also cancels itself up after activity has been destroyed!

Upvotes: 0

John - Aliferis
John - Aliferis

Reputation: 41

You could try to use a CountDownTimer. See more on how to use this here.

Upvotes: 0

OhhhThatVarun
OhhhThatVarun

Reputation: 4320

You can try this

val textViewsArray = arrayListOf(firsttxtview,secondtxtview...)

textViewsArray.forEachIndexed { index, textView->

    Handler().postDelayed({
        activity.runOnUiThread {
           textView.setText((array[index]).toString())
        }
    }, 5000 * index)
}

Upvotes: 1

Related Questions