Created
May 3, 2015 18:53
-
-
Save VladSumtsov/92ad6c78bcbce3c73a22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.corewillsoft.usetool.utils; | |
import android.app.Activity; | |
import android.content.SharedPreferences; | |
import android.content.res.Resources; | |
import android.os.Handler; | |
import com.corewillsoft.usetool.ui.fragments.LanguagesFragment; | |
import com.google.inject.Inject; | |
import java.util.Locale; | |
import roboguice.context.event.OnCreateEvent; | |
import roboguice.activity.event.OnRestartEvent; | |
import roboguice.event.EventManager; | |
import roboguice.event.Observes; | |
/** | |
* Recreates hosting {@link android.app.Activity} if the app {@link java.util.Locale} has been changed | |
*/ | |
public class LanguageSwitcher { | |
@Inject | |
private EventManager eventManager; | |
@Inject | |
private Resources resources; | |
@Inject | |
private Activity activity; | |
@Inject | |
private SharedPreferences preferences; | |
private Locale locale = null; | |
public void onActivityCreated(@Observes OnCreateEvent event) { | |
int index = preferences.getInt(LanguagesFragment.KEY_SELECTED_LANGUAGE, 0); | |
if (index > 0) { | |
LanguagesFragment.SupportedLanguage language = LanguagesFragment.SupportedLanguage.values()[index]; | |
locale = language.locale; | |
} else { | |
locale = resources.getConfiguration().locale; | |
} | |
} | |
@SuppressWarnings("unused") | |
public void onActivityRestarted(@Observes OnRestartEvent event) { | |
if (locale != null && !locale.getLanguage().equals(resources.getConfiguration().locale.getLanguage())) { | |
// added to avoid recreation Runtime exception in Android internals | |
new Handler(activity.getMainLooper()).postDelayed(new Runnable() { | |
@Override | |
public void run() { | |
activity.recreate(); | |
} | |
}, 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment