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

Compose中Box组件展开/收起时右侧边缘抖动问题求助

问题分析与解决

你的动画卡顿核心原因是状态管理逻辑不合理,导致Composable重组机制无法高效响应状态变化,具体问题和修复方案如下:

问题点拆解

  • 把isExpandedSavingCard定义在Activity成员变量中,未用remember包裹,导致Composable无法正确追踪状态变化,引发不必要的无效重组或状态更新延迟。
  • 额外引入savingCardWeight中间状态变量,增加了状态流转复杂度,容易出现状态不同步,拖慢动画响应效率。

修复后的代码

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

class TestClassTwo : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // 将状态移入Composable内部,用remember绑定生命周期,确保状态变化能被正确感知
            var isExpandedSavingCard by remember { mutableStateOf(true) }
            
            // 直接基于状态变量计算动画目标值,移除冗余中间状态
            val animation = animateFloatAsState(
                targetValue = if (isExpandedSavingCard) 0.50f else 1f,
                animationSpec = tween(
                    durationMillis = 400,
                    easing = LinearEasing
                )
            )

            Box(
                modifier = Modifier
                    .fillMaxWidth(animation.value)
                    .fillMaxHeight(0.5f)
                    .clickable {
                        isExpandedSavingCard = !isExpandedSavingCard
                    }
                    .background(color = Color.Blue)
            )
        }
    }
}

修改说明

  1. 将isExpandedSavingCard移至Composable内部并通过remember包裹,保证状态与Composable生命周期绑定,让Composable能精准响应状态变化,避免无效重组。
  2. 移除savingCardWeight变量,直接通过isExpandedSavingCard的状态计算动画目标值,简化状态流转逻辑,减少出错概率,提升动画响应效率。

调整后动画的状态更新会更高效,卡顿问题即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:54:26