-
-
Save avipars/725621e7718cea16fceea186f1413a6c to your computer and use it in GitHub Desktop.
Change the locale language inside the app
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
public class App extends Application { | |
public void onCreate(){ | |
super.onCreate(); | |
LocaleUtils.setLocale(new Locale("iw")); | |
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration()); | |
} | |
@Override | |
public void onConfigurationChanged(Configuration newConfig) { | |
super.onConfigurationChanged(newConfig); | |
LocaleUtils.updateConfig(this, newConfig); | |
} | |
} |
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
public class BaseActivity extends AppCompatActivity { | |
public BaseActivity() { | |
LocaleUtils.updateConfig(this); | |
} | |
} |
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
import android.app.Application; | |
import android.content.res.Configuration; | |
import android.content.res.Resources; | |
import android.os.Build; | |
import android.view.ContextThemeWrapper; | |
import java.util.Locale; | |
public class LocaleUtils { | |
public static final String LAN_SPANISH = "es"; | |
public static final String LAN_PORTUGUESE = "pt"; | |
public static final String LAN_ENGLISH = "en"; | |
private static Locale sLocale; | |
public static void setLocale(Locale locale) { | |
sLocale = locale; | |
if(sLocale != null) { | |
Locale.setDefault(sLocale); | |
} | |
} | |
public static void updateConfig(ContextThemeWrapper wrapper) { | |
if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { | |
Configuration configuration = new Configuration(); | |
configuration.setLocale(sLocale); | |
wrapper.applyOverrideConfiguration(configuration); | |
} | |
} | |
public static void updateConfig(Application app, Configuration configuration) { | |
if(sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { | |
//Wrapping the configuration to avoid Activity endless loop | |
Configuration config = new Configuration(configuration); | |
config.locale = sLocale; | |
Resources res = app.getBaseContext().getResources(); | |
res.updateConfiguration(config, res.getDisplayMetrics()); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment