Pal*_*uri 7 android locale internationalization android-jetpack-compose
我正在尝试为我正在开发的应用程序构建一个应用程序内语言切换器,但我已经尝试了 Stackoverflow 上几乎所有可用的方法。我还尝试了这里的官方指南https://developer.android.com/guide/topics/resources/app-languages#api-implementation
似乎什么都不起作用。这是 GitHub 上的代码https://github.com/bauripalash/Pankti-Android
这是我要更改语言的设置屏幕
fun Context.findActivity() : Activity? = when(this){
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
fun changeLanguage( context: Context , language: String ){
context.findActivity()?.runOnUiThread {
val appLocale = LocaleListCompat.forLanguageTags(language)
AppCompatDelegate.setApplicationLocales(appLocale)
//context.findActivity()?.recreate()
}
//context.findActivity()?.recreate()
}
Run Code Online (Sandbox Code Playgroud)
这是主要活动
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("bn"))
AppCompatDelegate.getApplicationLocales()[0]?.let { Log.i("MainView" , it.displayLanguage) }
setContent {
PanktiMobTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainView()
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
重新创建活动也不起作用。
我几乎尝试了在 Stackoverflow 和其他地方能找到的所有方法。
Android context.getResources.updateConfiguration() 已弃用
使用 JetPack Compose 更改 Android 语言
我知道这里有很多人问这种类型的问题。但有人可以帮助我吗?
Dev*_*007 11
为了正常工作,请将值文件夹中Themes.xml文件中的MaterialTheme更改为AppCompat主题。
检查此博客以从头开始添加 Android 本地化或多语言 -单击此处
示例: themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- <style name="Theme.SatCat" parent="android:Theme.Material.Light.NoActionBar" />-->
<style name="Theme.SatCat" parent="Theme.AppCompat.Light" />
</resources>
Run Code Online (Sandbox Code Playgroud)
更新:对于 Jetpack Compose,
即使您在AndroidManifest.xml中添加MainActivity的android:theme="@style/Theme.SatCat"。它只能在 ComponentActivity 的 setContent{} 之上工作。因为,我们在setContent{}中添加了MaterialTheme。
解决方案 :
我们必须将 MainActivity 扩展ComponentActivity更改为AppCompatActivity,并使用主题作为 Manifest 中的 AppCompat Theme。
更多信息: 如果我们将 AppCompatDelegate.setApplicationLocales() 与MaterialTheme一起使用,则 Context 将变为 NULL,因此无法创建Locale Manager。
由于sActivityDelegates为空,因此 Context为null。
但是,一旦我将主题更改为AppCompat。它开始工作了。
告诉我们,如果有人知道sActivityDelegates,以及为什么它没有在 postCreate 的生命周期中添加,正如他们在评论中提到的那样。我们将不胜感激。
| 归档时间: |
|
| 查看次数: |
1736 次 |
| 最近记录: |