简体   繁体   中英

How to make blinking imageview in Android?

I would like to make imageView with some background blinking. I will set frequency and it will have to blink. I think that blinking = View.VISIBLE/View.GONE or I'm wrong? As I understand I can use kotlin Coroutines for solving this task because ordinary recursion won't help me. So, in my activity class I have added such method:

private fun showAlertDialog() {
        val dialogue = Dialog(this)
        var scope = GlobalScope
        dialogue.setContentView(R.layout.alert_dialogue)

        dialogue.window?.apply {
            attributes =
                window!!.attributes.apply { width = LinearLayoutCompat.LayoutParams.MATCH_PARENT }
        }

        val img = dialogue.findViewById<ImageView>(R.id.rgb_main_item)

        scope.launch {
            while(true) {
                runOnUiThread {
                    img.visibility = if (img.visibility == View.GONE) View.VISIBLE else View.GONE
                }


                delay(140)
            }
        }

        img.setOnClickListener {
            scope = GlobalScope
        }

        dialogue.setCanceledOnTouchOutside(false)

        dialogue.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogue.show()

    }

as you can see in the code above - it creates dialogue with single image and transparent background. In general it works as I mentioned above, but sometimes I don't know what happens and I see small delay between two blinks and then frequency is damaged due to this delay and after some moments it blinks good again. I think that I did smth wrong with Coroutine function call or in another place.

Instead of setting visibility to VISIBLE/GONE , better to use alpha property to get the most realistic effect

 val blinkAnim = ObjectAnimator.ofFloat(img, View.ALPHA, 0F,1F)
 blinkAnim.repeatCount = ObjectAnimator.INFINITE
 blinkAnim.repeatMode = ObjectAnimator.REVERSE
 blinkAnim.duration = 140
 blinkAnim.start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM