gpt4 book ai didi

Android Compose MVVM - 如何在不带参数的 Composable 函数中引用 viewModel 对象?

转载 作者:行者123 更新时间:2023-12-05 00:14:41 25 4
gpt4 key购买 nike

@Composable ContentFeed() 函数如何访问在 Activity 中创建的 viewModel?依赖注入(inject)?或者这是一种错误的做事方式? viewModel 应该始终只有一个实例。

// MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel by viewModels<MainViewModel>()
setContent {
PracticeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
PulseApp(viewModel)
}
}
}
}

// TabItem.kt
typealias ComposableFun = @Composable () -> Unit

sealed class TabItem(var icon: Int, var title: String, var content: ComposableFun) {
object Feed : TabItem(R.drawable.ic_baseline_view_list_24, "Feed", { ContentFeed() })
}

// Content.kt
@Composable
fun ContentFeed() {
// I need viewModel created in MainActivity.kt here
}

最佳答案

在任何可组合项中,您都可以使用 viewModel<YourClassHere>() :

Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.

目前,Compose 中唯一的异常(exception)是当您使用 Compose 导航时,它未绑定(bind)到 Activity/fragment 。在这种情况下,商店所有者绑定(bind)到每条路线,请参阅 thisthis有关如何在路线之间共享商店所有者的答案。

查看有关 View 模型 Compose 的更多信息 documentation .

关于Android Compose MVVM - 如何在不带参数的 Composable 函数中引用 viewModel 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70334733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com