Skip to content

Instantly share code, notes, and snippets.

@Rolf-Smit
Created November 1, 2022 10:56
Show Gist options
  • Save Rolf-Smit/645645394bf5d51e218884b78a96cde3 to your computer and use it in GitHub Desktop.
Save Rolf-Smit/645645394bf5d51e218884b78a96cde3 to your computer and use it in GitHub Desktop.
/*
* @author Rolf Smit
* Copyright: © Rolf Smit / NeoTech Software
*/
package org.neotech.library.utilities;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import androidx.annotation.NonNull;
import java.util.Locale;
import static android.os.Build.VERSION_CODES.N;
public class LocaleManager {
/**
* A LocaleProvider or locale String can often not be injected because injection almost
* always happens after attachBaseContext. Therefore it could make sense to let the Application
* class inherit from LocaleProvider so that everywhere where you have access to a Context
* object you can also get the LocaleProvider. This method does exactly that, it gets the
* Application Context then casts that to a LocaleProvider to get the desired locale from.
*/
public static Context setLocale(@NonNull Context context) {
return setLocale(context, ((LocaleProvider) context.getApplicationContext()));
}
public static Context setLocale(@NonNull Context context, @NonNull LocaleProvider localeProvider) {
return setLocale(context, localeProvider.getDesiredLanguageCode());
}
/**
* Call this method in:
* - Application.attachBaseContext(setLocale(...))
* - Application.onConfigurationChanged() { setLocale(...) }
* - Activity.attachBaseContext(setLocale(...))
*
* @param context current Context.
* @param language the desired language
* @return Context with updated configuration.
*/
public static Context setLocale(@NonNull Context context, @NonNull String language) {
return updateResources(context, language);
}
private static Context updateResources(@NonNull Context context, @NonNull String language) {
final Locale newLocale = new Locale(language);
final Resources resources = context.getResources();
if (getLocale(context).getLanguage().equals(newLocale.getLanguage())) {
return context;
}
Locale.setDefault(newLocale);
final Configuration config = new Configuration(resources.getConfiguration());
config.setLocale(newLocale);
context = context.createConfigurationContext(config);
return context;
}
@NonNull
public static Locale getLocale(Context context) {
Configuration config = context.getResources().getConfiguration();
return Build.VERSION.SDK_INT >= N ? config.getLocales().get(0) : config.locale;
}
public interface LocaleProvider {
String getDesiredLanguageCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment