You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Kotlin实现按钮点击变色并2秒恢复原色

Android按钮点击变色后2秒恢复原始颜色实现方案

原代码已经实现了点击按钮根据判断结果切换绿色/红色,但缺少2秒后恢复原始颜色的逻辑,以下是完整实现:

核心思路

  1. 提前保存按钮的原始背景状态(颜色或Drawable),避免恢复时丢失初始样式
  2. 使用延迟任务,2秒后将按钮背景重置为原始状态

完整代码(Kotlin协程实现,推荐)

import android.graphics.Color
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class YourGameActivity : AppCompatActivity() {
    // 假设这是你要判断的目标值,替换成实际业务逻辑的数值
    private val result = 10

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game) // 替换为你的布局文件

        val bttGameNum = findViewById<Button>(R.id.BttGameNum)
        // 保存按钮原始背景颜色(如果背景是Drawable,直接保存background对象即可)
        val originalBgColor = bttGameNum.background.defaultColor

        bttGameNum.setOnClickListener {
            val inputNumber = bttGameNum.text.toString().toInt()
            // 根据判断结果设置对应颜色
            val targetColor = if (inputNumber == result) Color.GREEN else Color.RED
            bttGameNum.setBackgroundColor(targetColor)

            // 2秒后恢复原始背景
            CoroutineScope(Dispatchers.Main).launch {
                delay(2000) // 延迟2000毫秒(2秒)
                bttGameNum.setBackgroundColor(originalBgColor)
            }
        }
    }
}

备选方案(Handler实现)

如果项目未使用协程,也可以用Handler完成延迟:

import android.os.Handler
import android.os.Looper

// 替换上述代码中的协程部分
Handler(Looper.getMainLooper()).postDelayed({
    bttGameNum.setBackgroundColor(originalBgColor)
}, 2000)

注意事项

  • 如果按钮背景是自定义Drawable(比如xml中的shape),不要用defaultColor获取,直接保存原始background对象,恢复时赋值bttGameNum.background = originalBackground即可
  • 确保result变量已正确定义并赋值,避免空指针或类型转换错误

内容的提问来源于stack exchange,提问作者Daniel Neves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:58:22