有什么方法可以避免在Android(Kotlin)中连续输入相同的代码

时间:2019-07-04 02:16:43

标签: android animation kotlin imageview dry

我正在寻找有关是否可以在此处使用相同参数,而不是一遍又一遍地复制和粘贴相同代码的建议。

我正在尝试在App上移动块以产生视觉效果。屏幕上有一堆图像块(imageViews),我希望它们中的大多数都进行相同的动作,但是,我知道经常会教DRY(不要重复自己),而且我认为这确实是在这样做。有什么办法可以不不断重复我自己?

        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)

我希望能够使用相同的代码块而无需 必须连续复制并粘贴多个imageView。

2 个答案:

答案 0 :(得分:0)

只需使用这样的动态参数创建一个辅助函数

private fun setupAnimation(scanner: Scanner, imageView: Imageview) {
    scanner = (imageView)
    val animation = TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 1.0f,
            TranslateAnimation.RELATIVE_TO_PARENT, -1.0f
    )
    animation.setDuration(2500)
    animation.setRepeatCount(-1)
    animation.setRepeatMode(Animation.REVERSE)
    animation.setInterpolator(LinearInterpolator())
    scanner.setAnimation(animation)
}

您可以多次调用此函数

答案 1 :(得分:0)

您可以使用辅助函数来减少冗余代码,也可以使用kotlin的作用域函数来使代码清晰。

/**
 * 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
    }
相关问题