【问题标题】:How to set a custom Context in Jetpack Compose?如何在 Jetpack Compose 中设置自定义上下文?
【发布时间】:2021-11-02 22:51:24
【问题描述】:

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

在活动和片段中,我可以简单地替换 getContext()attachBaseContext(newBase: Context?) 方法中的上下文,但如何在 Jetpack Compose 中执行此操作?

Jetpack Compose 确实有这些 Context 方法:LocalConfiguration.currentLocalContext.current。我喜欢这是多么简单,但我无法找到这个 Context 对象的初始化位置。一开始我以为是在父Activity中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))
}

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    您可以尝试使用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()
                }
            }
        }
    }
    

    解决原始问题的另一种更 Compose 方法是创建自己的字符串保持器,例如 LocalStrings,类似于 this answer 中所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-03
      • 2022-11-10
      • 2023-01-03
      • 2021-12-17
      • 1970-01-01
      • 2021-12-17
      • 2023-01-17
      • 1970-01-01
      相关资源
      最近更新 更多