Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.


Cyclic property animator in Native View subclass (e.g. Flashing ImageView)

We show a method by which native View behavior can be overridden and a property changed in a cyclic sequence. For demonstration, we subclass an ImageView and set its alpha property to cycle between two defined values continuously

First, we define the subclass programmatically

// required constructor signature
class FlashingImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int): ImageView(context, attrs, defStyleAttr) {

    // define the upper and lower limits to the alpha property
    enum class Alphas(val value: Float) {

    // time duration between upper and lower limits 
    val duration: Long = 700L

    // required constructor signatures
    constructor(context: Context) : this(context, null)

    // post a runnable which will start the flashing sequence when this
    // ImageView is ready
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
        this.post(object: Runnable {
            override fun run() {

    // define the starting property value and start the flashing sequence
    fun startAnimation() {

    // this runnable restarts each step in the flashing sequence
    val runnable = object: Runnable {
        override fun run() {

    // swap the target property value for the animation and start 
    // an animation that will call our runnable on completion 
    fun step() {
        val newAlpha = if(this.alpha.equals(Alphas.lower.value))


This subclass can be utilized in XML layout as follows:


Note: it is recommended to switch off this type of continuous animation when it is not needed, not only to save CPU, also to avoid errors if attempting to use the Layout Inspector in Android Studio.

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?