https://kotlinlang.org logo
Title
k

KV

10/23/2020, 5:49 AM
what is the the best way to write the below code? In the below code I have 9 buttons but wha if I have more then 9 button and set the text to all the buttons. Do we have any simpler way to write this method?
private fun setupPinKeypad() {
        binding.pinCodeLayout.btn0.text = ZERO.toString()
        binding.pinCodeLayout.btn1.text = ONE.toString()
        binding.pinCodeLayout.btn2.text = TWO.toString()
        binding.pinCodeLayout.btn3.text = THREE.toString()
        binding.pinCodeLayout.btn4.text = FOUR.toString()
        binding.pinCodeLayout.btn5.text = FIVE.toString()
        binding.pinCodeLayout.btn6.text = SIX.toString()
        binding.pinCodeLayout.btn7.text = SEVEN.toString()
        binding.pinCodeLayout.btn8.text = EIGHT.toString()
        binding.pinCodeLayout.btn9.text = NINE.toString()
    }
g

gildor

10/23/2020, 5:53 AM
only extract some code duplications, but it wouldn’t help enourmously, will be just a bit cleaner, without duplicating
binding.pinCodeLayout
,
text
and
toString()
I don’t think there is better way, if you use generated acceors to views
k

KV

10/23/2020, 5:57 AM
Yes thank you for response. Even I am thinking the same. 🙂
g

gildor

10/23/2020, 6:30 AM
if you have dynamic views, you always can just iterate on them
👍 1
m

Matt Rea

10/24/2020, 12:49 AM
val buttonText = listOf(ONE, TWO, THREE, FOUR...).map { it.toString() } binding.pinCodeLayout.children.filterIsInstance<Button>().forEachIndexed { index, button -> button.text = buttonText[index] }
Something like that would work. Wrote on my phone, so may not be 100% correct syntax
children requires the core-ktx jetpack library
k

KV

10/26/2020, 5:40 AM
thanks for the help 🙂
What is the use of
children
? I am getting
Unresolved reference: children
g

gildor

10/26/2020, 5:59 AM
It’s an ktx extension in androidx.core.view
you can just replace it with getChildAt(i)
👍 1