给View添加一个扩展函数~~~

直接上代码,里面有注释,不懂的可以评论提问题哦~~~~ 

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View

/**
 * 添加点击缩放效果
 */
// 消除警告
@SuppressLint("ClickableViewAccessibility")
// 参数为:缩小比例、缩小的变化时间
fun View.addClickScale(scale: Float = 0.9f, duration: Long = 150) {
    this.setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                this.animate().scaleX(scale).scaleY(scale).setDuration(duration).start()
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                this.animate().scaleX(1f).scaleY(1f).setDuration(duration).start()
            }
        }
        this.onTouchEvent(event)
    }
}

使用方法(介绍使用的四种情况):

button.addClickScale(0.8f,100) // 缩小20%、缩小持续时间100ms
button.addClickScale(0.8f) // 缩小20%、缩小持续时间使用默认值150ms
button.addClickScale(duration = 100) // 缩小使用默认10%、缩小持续时间100ms
button.addClickScale() // 缩小使用默认10%、缩小持续时间使用默认值150ms
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐