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

Android Kotlin中如何创建仅显示数毫秒的圆形不确定进度条?

解决Circular Indeterminate ProgressBar仅显示数毫秒的问题

你当前的代码无法正常显示进度条,因为在同一个UI线程同步调用中,View.VISIBLE和View.INVISIBLE的状态变更会被系统合并执行,进度条根本来不及渲染就被隐藏了。以下是几种可行的实现方式:

方式一:使用View的postDelayed方法

利用View自带的延迟任务API,确保隐藏操作在指定毫秒后执行:

fun showProg() {
    binding.progBar.visibility = View.VISIBLE
    // 替换500为你需要显示的毫秒数
    binding.progBar.postDelayed({
        binding.progBar.visibility = View.INVISIBLE
    }, 500)
}

方式二:使用Kotlin协程(推荐)

结合Lifecycle协程,更贴合Kotlin项目的写法,还能自动关联页面生命周期避免内存泄漏:

fun showProg() = lifecycleScope.launch {
    binding.progBar.visibility = View.VISIBLE
    delay(500) // 替换为目标显示时长(毫秒)
    binding.progBar.visibility = View.INVISIBLE
}

注意事项

  • 调整delay或postDelayed的第二个参数值,即可控制进度条显示的时长
  • 如果页面可能在进度条隐藏前销毁,协程方案会自动取消任务;使用postDelayed时,建议在页面销毁前调用binding.progBar.removeCallbacksAndMessages(null)清理延迟任务,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:15:42