#android #locale
Как правильно локализовать приложение на андроид, чтобы можно было в настройках например
кликнуть на radiobutton или checkbox и устанавливался выбранный язык. Я себе это как
представляю, сделать, либо замещать весь текст в активити текстом другого языка при
выборе, либо создать новые активити с другими языками и уже при выборе другого языка
менять просто активити, либо еще какие-то есть мне не известные способы. Может кто-то
сможет посоветовать рабочий способ.
Ответы
Ответ 1
Если необходимо менять язык на лету, делайте следующее. 1) Создаете ресурсы в string.xmlпотом ресурсы для второго языка, например Французский values-fr/string.xml Change Language Hello Welcome, 2) Создаете класс помощник package devdeeds.com.changelanguage; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.preference.PreferenceManager; import java.util.Locale; public class LocaleHelper { private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; public static Context onAttach(Context context) { String lang = getPersistedData(context, Locale.getDefault().getLanguage()); return setLocale(context, lang); } public static Context onAttach(Context context, String defaultLanguage) { String lang = getPersistedData(context, defaultLanguage); return setLocale(context, lang); } public static String getLanguage(Context context) { return getPersistedData(context, Locale.getDefault().getLanguage()); } public static Context setLocale(Context context, String language) { persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language); } return updateResourcesLegacy(context, language); } private static String getPersistedData(Context context, String defaultLanguage) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); return preferences.getString(SELECTED_LANGUAGE, defaultLanguage); } private static void persist(Context context, String language) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language); editor.apply(); } @TargetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration(); configuration.setLocale(locale); return context.createConfigurationContext(configuration); } @SuppressWarnings("deprecation") private static Context updateResourcesLegacy(Context context, String language) { Locale locale = new Locale(language); Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.locale = locale; resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context; } } 3) Меняете язык public class MainActivity extends AppCompatActivity { private String mLanguageCode = "fr"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //меняем Английский на Французский по клику на кнопку findViewById(R.id.btnChangeLangView).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Change Application level locale LocaleHelper.setLocale(MainActivity.this, mLanguageCode); //Пересоздаем Активити с новым языком. recreate(); } }); } } Если надо, можете запомнить выбранный язык в SharedPreference и в onCreate() сетить методом LocaleHelper.setLocale(MainActivity.this, mLanguageCode). первоисточник Changer de langue Bonjour Bienvenue,
Комментариев нет:
Отправить комментарий