treewalker
treewalker

Reputation: 109

How to keep changing background color in Kotlin?

I want to keep the background changed like a disco screen. But in this code, the only blue color is shown. What should I fix to change color kept changed?

var bgColor = 1
        val bgDrawableIds = intArrayOf(
            R.drawable.purple,
            R.drawable.red,
            R.drawable.blue,
        )
        bgColor++
        disco_display.background = resources.getDrawable(bgDrawableIds[bgColor % bgDrawableIds.size])
    

xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/disco_display"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white" />

</androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 0

Views: 410

Answers (1)

Tenfour04
Tenfour04

Reputation: 93629

Wrap it in a coroutine:

lifecycleScope.launch {
    while (true) {
        disco_display.background = resources.getDrawable(bgDrawableIds[++bgColor % bgDrawableIds.size])
        delay(200L)
    }
}

Upvotes: 1

Related Questions