Search code examples
androidanimationkotlinimageviewdry

Is there any way to avoiding typing this same code continuously in Android(Kotlin)


I am looking for advice on if its possible to use the same parameters here instead of copying and pasting the same code over and over again.

I am trying to move blocks around on an App for visual affects. There are a bunch of blocks(imageViews) on the screen and I want most of them to make the same motions, however, i know DRY (Don't repeat yourself) is taught often and i see this as literally doing that. Is there any way to do this without continuously repeating myself?

        var mScanner = (imageView1)
        var mAnimation = TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 1.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, -1.0f
        )
        mAnimation.setDuration(2500)
        mAnimation.setRepeatCount(-1)
        mAnimation.setRepeatMode(Animation.REVERSE)
        mAnimation.setInterpolator(LinearInterpolator())
        mScanner.setAnimation(mAnimation)

        var mScanner2 = (imageView2)
        var mAnimation2 = TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 1.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, -1.0f
        )
        mAnimation2.setDuration(2500)
        mAnimation2.setRepeatCount(-1)
        mAnimation2.setRepeatMode(Animation.REVERSE)
        mAnimation2.setInterpolator(LinearInterpolator())
        mScanner2.setAnimation(mAnimation2)

I am hoping to be capable of using the same block of code without having to copy and paste it continuously for multiple imageViews.


Solution

  • You can use a helper function for reducing the redundant code, also you can use kotlin's scope function to make your code clean.

    /**
     * Helper function for setting animation to a image view
     */
    private fun setupAnimation(imageView: ImageView) {
    
            val animation = TranslateAnimation(
                    TranslateAnimation.ABSOLUTE, 0f,
                    TranslateAnimation.ABSOLUTE, 0f,
                    TranslateAnimation.RELATIVE_TO_PARENT, 1.0f,
                    TranslateAnimation.RELATIVE_TO_PARENT, -1.0f
            )
    
            animation.apply {
                duration = 2500
                repeatCount = -1
                repeatMode = Animation.REVERSE
                interpolator = LinearInterpolator()
            }
            imageView.animation = animation
        }