How can I choose a random color in Kotlin from a list? I couldn't find anything related to this topic...
Thanks.
Asked
Active
Viewed 2,719 times
-3

Markus Kauppinen
- 3,025
- 4
- 20
- 30
-
could you give more details? – Ignacio Tomas Crespo Sep 04 '20 at 06:27
-
Yes. So I want to choose a random number from my list in Kotlin and to change my Button background to that random color. Hope that makes sense. Thanks for your comment – Sep 04 '20 at 06:28
-
I don't quite get what you mean by *generate (...) from a list*. As far as I know, you could *choose* a random color from a list or *generate* one from RGB values, maybe. – deHaar Sep 04 '20 at 06:32
-
1Sorry if I didn't make it clear. I mean to choose a random color from a list – Sep 04 '20 at 06:33
-
2`couldn't find anything` because what you're trying to do is 2 separate tasks. picking a random value from an array and populating an array with colors. it's useful to know how to split up tasks – a_local_nobody Sep 04 '20 at 06:43
-
I'll keep that in mind next time – Sep 04 '20 at 06:45
3 Answers
5
You can define a color array and use random()
func to get random color from it
val colors = arrayOf(
Color.parseColor("#FFFFFF"),
Color.parseColor("#000000"),
Color.parseColor("#FF8F00"),
Color.parseColor("#EF6C00"),
Color.parseColor("#D84315"),
Color.parseColor("#37474F"),
//...more
)
val randomColor = colors.random()
Or random generate a color
val rnd = Random.Default //kotlin.random
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))

Son Huynh
- 839
- 1
- 7
- 11
2
In Kotlin Random is used as a companion object so this should work. You will get random value between 0 and 255:
val color = Color.argb(255, Random.nextInt(0, 255), Random.nextInt(0, 255), Random.nextInt(0, 255))
EDIT:
I saw that you commented and you want to obtain color from the list. Thanks to Kotlin we have a lot of additional functionalities on collections, so you can use random()
function to obtain random object from the list:
val colors = arrayListOf(color1, color2, color3, color4)
val randomColor = colors.random()

Mariusz Brona
- 1,549
- 10
- 12
0
Helpful.
Java
Random rnd = new Random();
paint.setARGB(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
Kotlin
val rnd = Random()
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
myView.setBackgroundColor(color)

Arda Kazancı
- 8,341
- 4
- 28
- 50
-
-
-
https://stackoverflow.com/questions/45685026/how-can-i-get-a-random-number-in-kotlin Random Implement Problem HelpFul – Arda Kazancı Sep 04 '20 at 06:35