Skip to content

Instantly share code, notes, and snippets.

@macieknajbar
Last active July 8, 2020 07:22
Show Gist options
  • Save macieknajbar/8b5c843d3de3224ad6c7768d25470b8e to your computer and use it in GitHub Desktop.
Save macieknajbar/8b5c843d3de3224ad6c7768d25470b8e to your computer and use it in GitHub Desktop.
class ClickDrawable(layers: Array<out Drawable> = arrayOf()) : LayerDrawable(layers) {
private var wasPressed = false
private var mActive = false
private var canStart = true
private var mBounds = bounds
override fun isStateful(): Boolean {
return true
}
override fun onStateChange(state: IntArray?): Boolean {
val stateSet = state?.toSet() ?: emptySet()
var enabled = false
var pressed = false
for (s in stateSet) {
when (s) {
android.R.attr.state_enabled -> enabled = true
android.R.attr.state_pressed -> pressed = true
}
}
setClickActive(enabled && wasPressed && !pressed)
wasPressed = pressed
return super.onStateChange(state)
}
private fun setClickActive(active: Boolean) {
if (mActive != active) {
mActive = active
if (active && canStart) {
canStart = false
mBounds = copyBounds()
startAnimation()
}
}
}
private fun setBounds(value: Float) {
if (value == 1f) {
canStart = true
}
val x = mBounds.width()
val y = mBounds.height()
val factorX = (x * value).roundToInt()
val factorY = (y * value).roundToInt()
bounds = mBounds.run {
Rect(
right - factorX,
bottom - factorY,
factorX,
factorY
)
}
invalidateSelf()
}
private fun startAnimation() {
val anim = ObjectAnimator.ofFloat(this, "bounds", 0.99f, 0.95f, 1f)
anim.duration = 225
anim.interpolator = LinearInterpolator()
anim.start()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment