Home > Net >  Build list programatically in Android Kotlin
Build list programatically in Android Kotlin

Time:02-01

Any ideas how to create this list dinamically using some math functions or something? It looks really ugly like this. There isn't an exact pattern for how the colors are so I'm not sure how to do this. Help would be much appreciated.

val colorGradient = listOf(
    backgroundColor.copy(alpha = 1f),
    backgroundColor.copy(alpha = 0.95f),
    backgroundColor.copy(alpha = 0.95f),
    backgroundColor.copy(alpha = 0.95f),
    backgroundColor.copy(alpha = 0.9f),
    backgroundColor.copy(alpha = 0.9f),
    backgroundColor.copy(alpha = 0.9f),
    backgroundColor.copy(alpha = 0.85f),
    backgroundColor.copy(alpha = 0.85f),
    backgroundColor.copy(alpha = 0.85f),
    backgroundColor.copy(alpha = 0.85f),
    backgroundColor.copy(alpha = 0.8f),
    backgroundColor.copy(alpha = 0.8f),
    backgroundColor.copy(alpha = 0.7f),
    backgroundColor.copy(alpha = 0.7f),
    backgroundColor.copy(alpha = 0.6f),
    backgroundColor.copy(alpha = 0.55f),
    backgroundColor.copy(alpha = 0.5f),
    backgroundColor.copy(alpha = 0.5f),
    backgroundColor.copy(alpha = 0.4f),
    backgroundColor.copy(alpha = 0.3f),
    backgroundColor.copy(alpha = 0.2f),
    backgroundColor.copy(alpha = 0.1f),
    backgroundColor.copy(alpha = 0.05f),
    Color.Transparent,
    Color.Transparent
)

CodePudding user response:

Given that there is no real pattern, I would do it like this to make it more compact:

val gradients = listOf(1.0f, 0.95f, 0.95f, 0.95f, 0.9f, 0.9f, 0.9f, 0.85f, 0.85f, 0.85f, 0.85f, 0.8f, 0.8f, 0.7f, 0.7f, 0.6f, 0.55f, 0.5f, 0.5f, 0.4f, 0.3f, 0.2f, 0.1f, 0.0f, 0.0f)
val colorGradient = gradients.map { backgroundColor.copy(alpha = it) }

CodePudding user response:

You could also start with a list of count of each gradient step:

val colorGradient = listOf(1, 3, 3, 4, 2, 0, 2, 0, 1, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 1, 2)
  .flatMapIndexed { index, count -> List(count) { (1 - (index * 5) / 100.0).toFloat() } }
  •  Tags:  
  • Related