Skip to content

Commit 03db691

Browse files
nichu42Copilot
andcommitted
fix: recreate activity when language changes
AppCompatDelegate.setApplicationLocales() does not reliably recreate the running activity across all Android versions. Add an explicit recreate() call after persisting the locale so the UI reloads in the new language immediately. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 8e2ea83 commit 03db691

1 file changed

Lines changed: 15 additions & 1 deletion

File tree

app/src/main/java/de/nichu42/boxviewer/util/LocaleHelper.kt

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package de.nichu42.boxviewer.util
22

3+
import android.app.Activity
34
import android.content.Context
5+
import android.content.ContextWrapper
46
import androidx.appcompat.app.AppCompatDelegate
57
import androidx.core.os.LocaleListCompat
68
import de.nichu42.boxviewer.R
@@ -45,7 +47,8 @@ object LocaleHelper {
4547
}
4648

4749
/**
48-
* Persists the user's choice and applies it immediately.
50+
* Persists the user's choice, applies it immediately, and recreates the
51+
* current activity so the new locale is visible right away.
4952
*
5053
* @param tag Empty string means "follow system default"; otherwise a BCP-47 tag
5154
* from [SUPPORTED_LOCALES].
@@ -56,6 +59,7 @@ object LocaleHelper {
5659
.putString(KEY_APP_LANGUAGE, tag)
5760
.apply()
5861
applyLocale(tag)
62+
context.findActivity()?.recreate()
5963
}
6064

6165
/** Returns the saved language tag, or empty string for system default. */
@@ -79,4 +83,14 @@ object LocaleHelper {
7983
}
8084
AppCompatDelegate.setApplicationLocales(localeList)
8185
}
86+
87+
/** Walks up the [ContextWrapper] chain to find the hosting [Activity]. */
88+
private fun Context.findActivity(): Activity? {
89+
var currentContext = this
90+
while (currentContext is ContextWrapper) {
91+
if (currentContext is Activity) return currentContext
92+
currentContext = currentContext.baseContext
93+
}
94+
return null
95+
}
8296
}

0 commit comments

Comments
 (0)