https://kotlinlang.org logo
#compose
Title
# compose
s

Spikey Sanju

02/27/2021, 11:08 AM
Hi guys, I'm trying to create transparent chip view for genders
Male
&
Female
. I'm repeating this code block for two times here. Below code works but I guess it can be optimised. Any Suggestion? I have also attached image of the both chip views
Guys, I optimised in this way 🙌.. Thanks
j

Javier

02/27/2021, 11:18 AM
Yeah, I deleted the comment because I haven't finished to read the previous comment. It is better to put all related content in the same thread
s

Spikey Sanju

02/27/2021, 11:18 AM
Sure will do 👍
🙂 1
j

jossiwolf

02/27/2021, 11:52 AM
This works, but now you're essentially defining your models in your UI layer. You could think about extracting the data into a model:
Copy code
data class Gender(val name: String, val color: Color)

@Composable
fun ContentHost() {
    val genders = listOf(
        Gender("Male", Color.Blue),
        Gender("Female", Color.Red),
        Gender("Non-Binary", Color.Green)
    )
    Column {
       genders.forEach { gender ->
           ChipTag(gender.name, gender.color)
       }
    }
}
🆒 1
j

joakim

02/27/2021, 12:47 PM
@jossiwolf extra points for adding more genders.
❤️ 5
s

Spikey Sanju

02/27/2021, 1:02 PM
But the reason why I added only male & female genders because, I'm creating this application for dogs 😅.. #AndroidDevChallenge
j

joakim

02/27/2021, 1:26 PM
:D fair enough. Although who are we to assume the gender of our furry friends.
😄 3
j

Javier

02/27/2021, 2:06 PM
Maybe instead of a data class, I would use an enum
2
So if you add something later, you will not need to add it manually to the list or change something in the composable
s

Se7eN

02/27/2021, 2:40 PM
I'd use a sealed class
j

Javier

02/27/2021, 3:16 PM
Why a sealed class?
t

TheMrCodes

02/27/2021, 3:21 PM
If you use a enum you could say that the
GenderTag
function takes a
Gender
Object as parameter and Takes the name and color from there. The code could then look like this: (No guarantee that it works without small errors wrote it on my phone)
Copy code
enum class Gender(tagColor: Color) {
    Female(R.color.blue)
    Male(R.color.red)
}

fun GenderTag(gender: Gender) {
   ChipView(gender.name, colorResource(gender.color))
}
s

Se7eN

02/27/2021, 3:26 PM
@Javier Maybe if later I was required to have different colors (or some other properties) of the genders in different screens I'd be able to do that easily
4 Views