1

I have 3 buttons that has the same animation.

let's call them, button1, button2, button3.

button1
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
button2
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
button3
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()

But this is too long. I need something like...

with(button1+button2+button3).apply{
    this.animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
}

This will be clearer and simpler. I could make a list of the views but this method is also longer and massier.

Is there any features like that in Kotlin?

c-an
  • 3,543
  • 5
  • 35
  • 82
  • 1
    you could create your own custom button view and have all of these properties set up by default – a_local_nobody Feb 21 '22 at 07:33
  • This is what functions are for, just extract a function that does the stuff you want on a given view (probably an extension function) and use it repeatedly on different views – Joffrey Feb 21 '22 at 08:53
  • @Joffrey well, I don't think it's a good idea. If the function keeps using here and there, then I might consider. – c-an Feb 21 '22 at 12:23

2 Answers2

2
val buttons = listOf(button1, button2, button3)
buttons.forEach { 
    it.animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
}
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
2

extension function

fun Button.setUp() {
    this.animate()
        .setDuration(initialTime)
        .setInterpolator(DecelerateInterpolator())
        .alpha(1f)
        .start()
}
button1.setUp()
button2.setUp()
button3.setUp()
GHH
  • 1,713
  • 1
  • 8
  • 21
  • I don't think it's a good way. I only use Extension function for general ussage. If that function is used in one Activity or something then... I think that's not a good approach. – c-an Feb 21 '22 at 12:25
  • I still need to call `setUp()` three times in your example. – c-an Feb 21 '22 at 12:26
  • 2
    @c-an why do you think so? Do you never use private functions at all? Reusing a piece of code is exactly what functions are for - whether it's in the same file or not is irrelevant. It's also a very nice way to give a name to this unit of work that you're doing, so the reader understands what the point is without having to read it all. – Joffrey Feb 21 '22 at 14:02
  • In this answer, I still need to call setUp() three times. So, it's not the answer that I was looking for. – c-an Feb 21 '22 at 14:24