我正在尝试为我正在开发的应用程序构建一个应用程序内语言切换器,但我已经尝试了 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()
}
这是主要活动
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()
}
}
}
}
}
重新创建 Activity,也不起作用。
我几乎尝试了在 Stackoverflow 和其他地方能找到的所有方法。
Android context.getResources.updateConfiguration() 已弃用
使用 JetPack Compose 更改 Android 语言
我知道这里有很多人问这种类型的问题。但有人可以帮助我吗?
为了工作,请将值文件夹中的 Themes.xml 文件中的 MaterialTheme 更改为 AppCompat 主题。
查看此博客以添加 android 本地化或多语言 从头开始 - 单击此处
示例: 主题.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>
更新: 对于 Jetpack Compose,
即使您在 AndroidManifest.xml 中添加 MainActivity 的 android:theme="@style/Theme.SatCat"。它只能在 ComponentActivity 的 setContent{} 之上工作。因为,我们在 setContent{} 中添加了 MaterialTheme。
解决方案:
我们必须将MainActivity扩展ComponentActivity更改为AppCompatActivity,并在Manifest中使用主题作为AppCompat主题。
更多信息: 如果我们将 AppCompatDelegate.setApplicationLocales() 与 MaterialTheme 一起使用,Context 将变为 NULL,因此无法创建 Locale Manager。
Context 为空,因为 sActivityDelegates 为空。
但是,一旦我将主题更改为AppCompat。它开始工作了。
告诉我们,如果有人知道 sActivityDelegates,以及为什么它没有在 postCreate 的生命周期中添加,正如他们在评论中提到的那样。我们将不胜感激。
AppCompatDelegate.setApplicationLocales()
在调试版本下工作正常
但在发布中它不会更改界面语言(发布版本setApplicationLocales
适用于Android模拟器)