Walter Berggren
04/07/2021, 11:36 AMhiltNavGraphViewModel()
in a NavHost: Expected an activity context for creating a HiltViewModelFactory for a NavBackStackEntry but instead found: android.app.ContextImpl@78d1695
Walter Berggren
04/07/2021, 11:41 AMsetContent {
OverrideLocale(language.value, this) {
Navigation()
}
}
With OverrideLocale
defined as following:
@Composable
private fun OverrideLocale(language: String, mainActivity: AppCompatActivity, content: @Composable () -> Unit) {
val configuration = LocalConfiguration.current
configuration.setLocale(Locale(language))
val context = LocalContext.current.createConfigurationContext(configuration)
CompositionLocalProvider(
LocalOnBackPressedDispatcherOwner provides mainActivity,
LocalConfiguration provides configuration,
LocalContext provides context
) {
content()
}
}
Walter Berggren
04/07/2021, 11:43 AMHiltViewModelFactory
never seems to reach a point where it deems the context to be an activity:
@JvmName("create")
public fun HiltViewModelFactory(
context: Context,
navBackStackEntry: NavBackStackEntry
): ViewModelProvider.Factory {
val activity = context.let {
var ctx = it
while (ctx is ContextWrapper) {
if (ctx is Activity) {
return@let ctx
}
ctx = ctx.baseContext
}
throw IllegalStateException(
"Expected an activity context for creating a HiltViewModelFactory for a " +
"NavBackStackEntry but instead found: $ctx"
)
}
[...]
Walter Berggren
04/07/2021, 11:43 AMreturn@let ctx
above is never called.Walter Berggren
04/07/2021, 11:45 AMOverrideLocale
makes the code run just fine.FunkyMuse
04/07/2021, 11:58 AM@AndroidEntryPoint
to the activity hosting the composables?Albert Chang
04/07/2021, 12:36 PMWalter Berggren
04/07/2021, 12:54 PM@AndroidEntryPoint
Walter Berggren
04/07/2021, 1:12 PMWalter Berggren
04/07/2021, 2:02 PMcreateConfigurationContext
directly, I use ContextWrapper to update the getResources
call to use the next context but use the MainActivity for all other calls:
class ContextWithUpdatedResources(
private val resources: Context,
base: Context
) : ContextWrapper(base) {
override fun getResources(): Resources {
return resources.resources
}
}
My OverrideLocale
is defined as following:
@Composable
private fun OverrideLocale(language: String, mainActivity: MainActivity, content: @Composable () -> Unit) {
val configuration = LocalConfiguration.current
configuration.setLocale(Locale(language))
val resources = LocalContext.current.createConfigurationContext(configuration)
CompositionLocalProvider(
LocalOnBackPressedDispatcherOwner provides mainActivity,
LocalConfiguration provides configuration,
LocalContext provides ContextWithUpdatedResources(resources, mainActivity)
) {
content()
}
}
Ian Lake
04/07/2021, 2:22 PMLocalOnBackPressedDispatcher
also does the same context unwrapping, so overriding it isn't necessaryWalter Berggren
04/08/2021, 6:30 AM