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

Android中如何更新LinearProgressIndicator?动态值不生效问题

解决LinearProgressIndicator进度不更新问题

问题根源

你的代码存在几个关键问题,导致LPI无法动态更新进度:

  • 百分比计算时符号错误,且整数除法会丢失精度
  • 未处理预算为0的边界情况,可能产生无效值或崩溃
  • 进度值可能超出LPI的有效范围(默认0-100)
  • 可能未通过ViewBinding正确引用布局中的LPI控件

修复方案

  • 修正百分比计算逻辑:
    支出金额expenseAmount为负数(因totalAmount = 收入 - 支出,expenseAmount = totalAmount - 收入 = -支出),需先取绝对值,同时将数值转为浮点型避免整数除法:

    val spentPercent = if (budgetAmount == 0) 0.0 else (abs(expenseAmount).toDouble() / budgetAmount.toDouble()) * 100
    
  • 限制进度值范围:
    LPI进度默认范围是0到100,用coerceIn确保数值合法:

    val validProgress = spentPercent.coerceIn(0.0, 100.0).toInt()
    
  • 通过ViewBinding操作控件:
    确保操作的是布局中实际的LPI实例,用binding.progressIndicator代替直接的progressIndicator:

    binding.progressIndicator.setProgress(validProgress, true)
    

完整修正代码

private fun updateDashboard(binding: ActivityMainBinding) {
    val totalAmount = transactions.sumOf { it.amount }
    val budgetAmount = transactions.filter { it.amount > 0 }.sumOf { it.amount }
    val expenseAmount = totalAmount - budgetAmount
    // 修复百分比计算,处理预算为0的边界情况
    val spentPercent = if (budgetAmount == 0) 0.0 else (abs(expenseAmount).toDouble() / budgetAmount.toDouble()) * 100
    // 确保进度在LPI有效范围内
    val validProgress = spentPercent.coerceIn(0.0, 100.0).toInt()

    binding.apply {
        "₹ %.2f".format(totalAmount).also { balanceTV.text = it }
        "₹ %.2f".format(budgetAmount).also { budgetTV.text = it }
        "₹ %.2f".format(abs(expenseAmount)).also { expenseTV.text = it }
        "%.0f%%".format(abs(spentPercent)).also { spentPercentTV.text = it }
        "₹ %.0f".format(budgetAmount).also { budgetTV2.text = it }
        // 通过binding设置进度
        progressIndicator.setProgress(validProgress, true)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:45:08