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

Android 如何更改cardview的背景色5秒钟并恢复为以前的颜色,android,kotlin,android-recyclerview,Android,Kotlin,Android Recyclerview,当我从一个特定的活动开始时,我试图改变卡片视图的背景色5秒钟。 这是recyclerview的cardview。 但应用程序正在崩溃。我试过了,但没能摆脱 if (intent.hasExtra("post_Id")) { postId = intent.getIntExtra("post_Id", 0) Handler().postDelayed({ post_card_view.setBackgroundColor(Color.pa

当我从一个特定的活动开始时,我试图改变卡片视图的背景色5秒钟。 这是recyclerview的cardview。 但应用程序正在崩溃。我试过了,但没能摆脱

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

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

只需将代码更改为:

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)

您可以使用将执行倒计时的类

查看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.

        }

    }
您可以将其作为内部类在父级
活动
中实现,也可以根据需要独立声明

由于您实施了它,您完全有责任启动计时器

启动倒数计时器

参数1:倒计时时间//您要倒计时的时间

val mTimer = CountDownTimer(COUNT_DOWN_TIME ,COUNT_DOWN_INTERVAL ) //create Timer Instance
mTimer.start()  //start the timer
param2:COUNT\u DOWN\u INTERVAL//每次之后直到倒计时为止收到通知的时间

val mTimer = CountDownTimer(COUNT_DOWN_TIME ,COUNT_DOWN_INTERVAL ) //create Timer Instance
mTimer.start()  //start the timer
但是,停止计时器有两种方法

  • 倒计时将按正常方式过期(您已成功计数 5秒)

  • 由于某些原因,您可以自行取消计时器

  • 要取消倒计时,请执行以下操作:

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

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

    共享您的代码please@majidghafouri完成,它正在改变颜色,但如何停止处理程序,以便cardview进入以前的颜色使用计时器…正如@RonTLV所建议的,计时器比
    处理程序
    方便得多。签出
    CountDownTimer
    。5秒钟的第二个处理程序如何?它应该在runnable中完成运行操作后自动停止。您能给我看一下示例代码吗?它将对我更有帮助,而且上面的优化代码也有响应。第一个处理程序已“注册”,可在1秒内运行您的操作。然后第二个处理程序被“注册”以在6秒内运行您的操作(第一个处理程序之后5秒)。第一个处理程序中的操作完成后-处理程序“未注册”。第二个也一样。