Change Language while using Navigation Component API 24+
G

2

6

TL;DR We want to change the locale (API 24+) for a to be displayed fragments while all these fragments are going to be inside the same activity.

We are using NavHostFragment, and start_up_nav_graph.xml. This graph has multiple fragments i.e. Log-in, Onboarding, GDPR ..etc

In this flow, If after logging in we find that you are a German user, we try to change your locale to German. In the current scenario, all the up-coming fragments (such as onboarding and GDPR) are going to be displayed in the device's locale, not German.

We can't use attachBaseContext in the activity like this answer, because the activity has already been created.

Genip answered 9/8, 2019 at 8:54 Comment(0)
P
1

I'm experiencing same pain brother. i tried to do

NavigationUI.setupWithNavController(mToolbar,mNavController, mAppBarConfiguration);

but this is also not helping because Toolbar Title and Navigation Drawer items are using old resources and when i'm doing activity.recreate() then it's actually happening but when you close app and restart it again same problem...

Pasadena answered 21/11, 2019 at 11:11 Comment(1)
What I did was split it into two parts, the 1st part of the start-up flow in which I don't know the language of the user and the 2nd part which I know the language of the user. Once I have this information, I start the 2nd part and then I can attachBaseContext as I would usually do. Hope this helpsGenip
E
0

This is the best I could come up with .

Note:- This is just a hack and not a correct solution

Once a language is changed, save the language in sharepreferences , override all the required methods in the activity you have , use the language from share preferences . Send an event to Activity and in activity , once getting event in activity you can do 1 of the below 2 things

Option1 :-

recreate() . This works well but there is a issue with fragment backstack .

Option 2 :-

finish()
intent.putExtra("LANGUAGE_CHANGE", true)
startActivity(intent)   // or getIntent() if using java
overridePendingTransition(0, 0)

And in oncreate if you get LANGUAGE_CHANGE in intent then go to the required fragment .

Eucalyptol answered 28/11, 2020 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.