Как сделать чтобы пользователь мог менять локализацию внутри приложения? Почему у меня не срабатывает код?
Вот код, Toast message возникает, но язык надписей не меняется.
public class MainActivity extends AppCompatActivity {
Locale locale1;
Locale locale2;
Configuration configuration1;
Configuration configuration2;
TextView hello;
TextView eatMusli;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello = findViewById(R.id.hello);
eatMusli = findViewById(R.id.eat_musli);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ru:
locale1 = new Locale("ru");
Locale.setDefault(locale1);
configuration1 = new Configuration();
configuration1.locale = locale1;
getBaseContext().getResources().updateConfiguration(configuration1,
getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in Russia!", Toast.LENGTH_SHORT).show();
return true;
case R.id.en:
locale2 = new Locale("en");
Locale.setDefault(locale2);
configuration2 = new Configuration();
configuration2.locale = locale2;
getBaseContext().getResources().updateConfiguration(configuration2,
getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in England!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Так выглядят строки: в ru/string.xml:
<resources>
<string name="eat_musli">А давай жрать мюсли?</string>
<string name="hello">Привет!</string>
<string name="language">Язык</string>
<string name="ru">Русский</string>
<string name="en">Инглиш</string>
</resources>
в en/string.xml:
<resources>
<string name="eat_musli">Let\'s eat musli?</string>
<string name="hello">Hello!</string>
<string name="language">language</string>
<string name="en">english</string>
<string name="ru">russian</string>
</resources>
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
Попробуйте добавить перезагрузку активности:
recreate()
если же вам нужно незаметно перезагрузить активность, можно ознакомится здесь с вариантами.