I wanna change the locale in my APP... I read a lot of articles and now I have this code, it doesn't work and doesn't give me an error:
My LanguageActivity:
public class LanguageActivity : BaseActivity {
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Language); LanguageManager.ChangeLanguage(this, "fa"); Intent intent = new Intent(this, typeof(MainActivity)); intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask); StartActivity(intent); }
}
My BaseActivity:
public class BaseActivity : Activity {
protected override void AttachBaseContext(Context @base) { base.AttachBaseContext(LanguageManager.LoadLanguage(@base)); }
}
My LanguageManager:
public class LanguageManager {
private const string MYLANGUAGE = "myLanguage"; private const string MYPREF = "myPreference"; public static Context LoadLanguage(Context context) { var loadedLanguage = GetLanguage(context, Locale.Default.Language); return ChangeLanguage(context, loadedLanguage); } public static Context ChangeLanguage(Context context, string language) { SaveLanguage(context, language); if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { return ChangeForAPI24(context, language); } return ChangeForLegacy(context, language); } private static string GetLanguage(Context context, string Language) { var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private); return privatePreference.GetString(MYLANGUAGE, Language); } private static void SaveLanguage(Context context, string language) { var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private); var editor = privatePreference.Edit(); editor.PutString(MYLANGUAGE, language); editor.Apply(); } private static Context ChangeForAPI24(Context context, string language) { // for api >= 24 Locale locale = new Locale(language); Locale.Default = locale; var configuration = context.Resources.Configuration; configuration.SetLocale(locale); configuration.SetLayoutDirection(locale); return context.CreateConfigurationContext(configuration); } private static Context ChangeForLegacy(Context context, string language) { var locale = new Locale(language); Locale.Default = locale; var resources = context.Resources; var configuration = resources.Configuration; configuration.Locale = locale; resources.UpdateConfiguration(configuration, resources.DisplayMetrics); return context; }
}
Why doesn't it work? I read this and this. They're using the same method!
PS1: I have values-fa folder and Strings.xml there. When I change the language in the phone's setting, I see the changes. So it works when I change the locale on the phone!
PS2: I simplified the code, that's why I removed the SharedPreference part in LanguageActivity!
PS3: Download the project: Download