Reputation: 1351
I want to provide my users an in-app (NOT DEVICE-WIDE) locale (language) change. Thats why I setup the following code which triggers when the user clicks on a specific language:
private void setLocale(Locale locale) {
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
So far so good but since now I really don't know how to update/refresh all of my active activities (current activity and all activities in the back stack). Do I have to override onResume()
of each activity? Could there be a possibility to generalize that?
Upvotes: 3
Views: 894
Reputation: 22038
I would use an Eventbus library such as this one.
You could also create some sort of Settings, an OnLocaleChangedListener interface, let all Activities (or other classes) listen for changes, something like this:
public class LocaleSettings {
Locale locale;
List<OnLocaleChangedListener> listeners;
void changeLocale(Locale newLocale){
this.locale = newLocale;
for(OnLocaleChangedListener listener : listeners){
listener.localeChanged(newLocale);
}
}
void addListener(){
}
void removeListener(OnLocaleChangedListener toRemove){
}
interface OnLocaleChangedListener{
void localeChanged(Locale locale);
}
}
Upvotes: 2
Reputation: 3568
If they all extend Activity
, you could create a super class that has the locale check in onStart()
. Then you could extend your custom Activity
and only have to implement your locale check once.
Something like this:
public abstract class LocaleActivity extends Activity {
@Override
protected void onStart() {
setLocale(yourLocale);
}
}
Then, let's say you have an activity called MainActivity
. You could implement it, like so:
public class MainActivity extends LocaleActivity {
//no need to override onStart, because we inherit it, whenever the user starts this activity in any way, the locale will set.
}
Upvotes: 1