【问题标题】:Why does this code get executed twice? If recomposition... what triggers the recomposition?为什么这段代码被执行了两次?如果重组……是什么触发了重组?
【发布时间】:2023-02-02 22:39:33
【问题描述】:

我正在学习 Android Compose,我正在 github 中查看/使用来自 developers.android 的代码。 该项目是一个演示自适应屏幕的简单应用程序。 Sports App

一切正常,但我很困惑。

我将一个项目/行记录到 Logcat。我看到它被执行了两次?重组?是什么原因造成的?

【问题讨论】:

  • 还要记录 selectedSport 的哈希码,看看它是否为同一项目重新组合。

标签: android android-jetpack-compose compose-recomposition


【解决方案1】:

在你的代码中:

Log.i("info", "xxx")

Column(
    modifier = Modifier.padding(4.dp)
) {

    Box {
        Image(painter = painterResource(R.drawable.xx))
        Text()
    }

    Text(
        text = stringResource(R.string.app_name),
    )
}

stringResourcepainterResource 会导致重组。 在 compose 中,当某事触发重组时,它发生在最近的范围内。
但是 BoxColumn排队函数,这意味着两者都没有自己的重组范围。

在您的代码中,当 ImageText 被重组时,所有可组合项都被重组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多