如何在Jetpack Compose中设置自定义上下文? [英] How to set a custom Context in Jetpack Compose?

查看:27
本文介绍了如何在Jetpack Compose中设置自定义上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Jetpack Compose的问题。在我的应用程序的旧类(Activity和Fragment)中,我为我的自定义Resources包装器使用了一个定制的Context包装器。这是因为字符串资源值是从服务器下载的;字符串资源文件确实包含字符串ID,它们的值为空,并被服务器的值替换。

在活动和片段中,我可以简单地替换getContext()attachBaseContext(newBase: Context?)方法中的上下文,但在Jetpack Compose中如何做到这一点?

Jetpack Compose具有以下Context方法:LocalConfiguration.currentLocalContext.current。我喜欢它的直截了当,但我找不到这个上下文对象的起始位置。起初,我以为设置内容时是在attachBaseContext()方法的父活动中,但这个代码似乎没有用:

@AndroidEntryPoint
class MyComposeActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContent {
        ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
            MyComposeActivityScreen()
        }
    }
}

override fun attachBaseContext(newBase: Context?) {
    val language = Locale(Utils.getLanguage(newBase))
    super.attachBaseContext(MyCustomContextWrapper.wrap(MyCustomResourcesContextWrapper(newBase), language))
}

推荐答案

您可以尝试使用CompositionLocalProvider手动指定上下文:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    updateComposeView(this)
}

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(newBase)
    updateComposeView(newBase ?: this)
}

fun updateComposeView(context: Context) {
    setContent {
        CompositionLocalProvider(
            LocalContext provides context
        ) {
            ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
                MyComposeActivityScreen()
            }
        }
    }
}

解决原始问题的一种更复杂的方法是创建您自己的字符串符,如LocalStrings所示,如this answer所示。

这篇关于如何在Jetpack Compose中设置自定义上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆