Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
View extensions with click/press effect
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true" android:fillBefore="true">
<scale
android:duration="100"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.98"
android:toYScale="0.98" >
</scale>
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true" android:fillBefore="true">
<scale
android:duration="100"
android:fromXScale="0.98"
android:fromYScale="0.98"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1"
android:toYScale="1">
</scale>
</set>
fun View.clickTo(
pressEffect: Boolean = true,
debounceIntervalMs: Int = 700,
listener: (view: View?) -> Unit
) {
var lastTapTimestamp: Long = 0
this.setOnClickListener{
val currentTime = System.currentTimeMillis()
if (currentTime - lastTapTimestamp > debounceIntervalMs) {
lastTapTimestamp = currentTime
listener(it)
}
}
if(pressEffect) {
addPressEffect()
}
}
fun View.addPressEffect(){
val alphaAnimator: ValueAnimator = ObjectAnimator.ofFloat(this, View.ALPHA, 1f,0.7f).apply {
duration = 200
}
fun View.addPressEffect() {
val alphaAnimator: ValueAnimator = ObjectAnimator.ofFloat(this, View.ALPHA, 1f, 0.7f).apply {
duration = 200
}
fun isMotionEventInsideView(view: View, event: MotionEvent): Boolean {
val viewRect = Rect(
view.left,
view.top,
view.right,
view.bottom
)
return viewRect.contains(
view.left + event.x.toInt(),
view.top + event.y.toInt()
)
}
setOnTouchListener(
View.OnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
alphaAnimator.start()
// v.startAnimation(
// ScaleAnimation(1f,1f,0.98f,0.98f).apply {
// duration = 100
// fillAfter = true
// fillBefore = true
// pivotX = v.width /2f
// pivotY = v.height /2f
// interpolator = LinearInterpolator()
// }
// )
v.startAnimation(AnimationUtils.loadAnimation(context, R.anim.anim_press))
return@OnTouchListener true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
alphaAnimator.reverse()
// v.startAnimation(
// ScaleAnimation(0.98f,0.98f,1f,1f).apply {
// duration = 100
// fillAfter = true
// fillBefore = true
// pivotX = v.width /2f
// pivotY = v.height /2f
// interpolator = LinearInterpolator()
// }
// )
v.startAnimation(AnimationUtils.loadAnimation(context, R.anim.anim_release))
if (isMotionEventInsideView(v, event)) {
performClick()
}
return@OnTouchListener true
}
}
false
}
)
}
fun View.animateBubbleClickEffect() {
this.scaleX = 0.95f
this.scaleY = 0.95f
ViewCompat.animate(this).scaleX(1f).scaleY(1f).setInterpolator(
OvershootInterpolator()
).start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment