繁体   English   中英

如何更改cardview的背景颜色5秒并恢复到以前的颜色

[英]How to change background color of cardview for 5 seconds and revert into its previous color

当来自特定活动时,我正在尝试将卡片视图的背景颜色更改 5 秒钟。 它是recyclerview的cardview。 但是应用程序崩溃了。 我尝试了处理程序但无法摆脱。

 if (intent.hasExtra("post_Id")) {
        postId = intent.getIntExtra("post_Id", 0)

        Handler().postDelayed({
            post_card_view.setBackgroundColor(Color.parseColor("#E1F2F878"))
        }, 1000)
    }

您可以使用CountDownTimer class 来执行倒计时。

查看Kotlin片段:

private const val COUNT_DOWN_TIME = 5secs   
private const val COUNT_DOWN_TIME = 1sec   

 class TimeCounter : CountDownTimer(val COUNT_DOWN_TIME,val COUNT_DOWN_INTERVAL) {

        override fun onFinish() {

          // This method will be called after completion of COUNT_DOWN_TIME
          // Do your work here once the limit of 5secs is completed.

        }


        override fun onTick(timeLeftUntilFinish: Long) {

            //this method is called every COUNT_DOWN_INTERVAL, until the timer is finished
//So if COUNT_DOWN_INTERVAL = 1sec, this method is called every 1sec till the timer is completed.

        }

    }

您可以在父Activity中将其实现为内部 class ,也可以根据您的需要独立声明它。

既然你实现了它,你就完全负责启动计时器

启动CountDownTimer

param1:COUNT_DOWN_TIME // 你想倒计时的时间

param2:COUNT_DOWN_INTERVAL // 每次收到通知后到倒计时的时间

val mTimer = CountDownTimer(COUNT_DOWN_TIME ,COUNT_DOWN_INTERVAL ) //create Timer Instance
mTimer.start()  //start the timer

但是,停止计时器有两种方法

  1. 倒计时正常结束(您已成功计数 5 秒)

  2. 您出于某些原因自行取消了计时器。

取消CountDownTimer

mTimer.cancel() // stops Timer as soon as called, irrespective whether count-down was pending.

注意:这是不言而喻的,但仍然使用相同的 object 来启动和停止计时器。

只需将您的代码更改为:

Handler().postDelayed({
        post_card_view.setCardBackgroundColor(Color.parseColor("#E1F2F878"))
    }, 1000)
Handler().postDelayed({
        post_card_view.setCardBackgroundColor(previous color)
    }, 6000)

或者,如果您不需要延迟第一次更改,只需:

Handler().post {
        post_card_view.setCardBackgroundColor(Color.parseColor("#E1F2F878"))
    }
Handler().postDelayed({
        post_card_view.setCardBackgroundColor(previous color)
    }, 5000)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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