Skip to content

Instantly share code, notes, and snippets.

@luciofm

luciofm/AlphaSpan.kt

Created Apr 26, 2018
Embed
What would you like to do?
Animate alhpa of each character separately
package com.luciofm.playground
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.UpdateAppearance
class AlphaSpan(var alpha: Int) : CharacterStyle(), UpdateAppearance {
override fun updateDrawState(ds: TextPaint) {
ds.alpha = alpha
}
}
package com.luciofm.playground
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.SpannableString
import android.text.Spanned
import android.util.Property
import android.view.animation.BounceInterpolator
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
@SuppressLint("WrongConstant")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
buildAnimation()
}
private fun buildAnimation() {
val text = SpannableString("Hello World!")
val spans = ArrayList<AlphaSpan>(text.length)
text.forEachIndexed { index, c ->
val span = AlphaSpan(0)
spans.add(span)
text.setSpan(span, index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
var currentDelay = 0L
val animators = ArrayList<Animator>()
for (span in spans) {
val anim = ObjectAnimator.ofInt(span, ALPHA_SPAN_PROPERTY, 0, 255)
anim.interpolator = BounceInterpolator()
anim.duration = 1200
anim.startDelay = currentDelay
animators.add(anim)
anim.addUpdateListener {
text_view.text = text
}
currentDelay += 120L
}
val anim = AnimatorSet()
anim.playTogether(animators)
anim.start()
}
private val ALPHA_SPAN_PROPERTY = object : Property<AlphaSpan, Int>(Int::class.java, "ALPHA_SPAN_PROPERTY") {
override fun set(span: AlphaSpan, value: Int) {
span.alpha = value
}
override fun get(span: AlphaSpan) = span.alpha
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.