Compose 中的状态
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
了解如何在基于 Compose 的应用中建立和管理状态,以及如何配置界面以响应状态变化。了解如何创建可观察状态、如何在重组或配置更改后保留状态,以及如何构建可组合项以实现最佳数据流。
要点
- 如果应用的状态是可组合项的内部状态,请使用
remember
在重新组合期间保留状态。
- 使用
rememberSaveable
在配置更改后保留状态。
- 状态提升是一种编程模式,在这种模式下,您可以将状态移至可组合项的调用方。尽可能使用状态提升来提高可组合项的可重用性和可测试性。
- 使用
ViewModel
类在可观察状态容器中存储公开状态,更好地封装状态,并为界面创建单一真相来源。
资源
包含本指南的集合
本指南属于以下精选快速入门集合,这些集合涵盖了更广泛的 Android 开发目标:
Compose 基础知识(视频合集)
本系列视频介绍了各种 Compose API,可让您快速了解可用 API 以及如何使用它们。
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[null,null,["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# State in Compose\n\n\u003cbr /\u003e\n\nLearn how to establish and manage state in your Compose-based app and how\nto configure the UI to react to changes in state. See how to create observable\nstates, how to retain state across recompositions or configuration changes, and\nhow to structure your composables for optimal data flow. \n\nKey points\n----------\n\n- If your app's state is internal to a composable, use [`remember`](/reference/kotlin/androidx/compose/runtime/package-summary#remember(kotlin.Function0)) to persist the state across re-composition.\n- Use [`rememberSaveable`](/reference/kotlin/androidx/compose/runtime/saveable/package-summary#rememberSaveable(kotlin.Array,androidx.compose.runtime.saveable.Saver,kotlin.String,kotlin.Function0)) to persist the state across configuration changes.\n- *State hoisting* is a programming pattern where you move the state to the caller of a composable. Where possible, use state hoisting to make the composable more reusable and testable.\n- Use the [`ViewModel`](/reference/androidx/lifecycle/ViewModel) class to hold an exposed state in an observable state holder, better encapsulating the state and creating a single source of truth for the UI.\n\nResources\n---------\n\n- [Codelab: State in Jetpack Compose](/codelabs/jetpack-compose-state#0)\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\n### Compose basics (video collection)\n\nThis series of videos introduces various Compose APIs, quickly showing you what's available and how to use them. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/compose-basics) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]