我遇到了一个很奇怪的问题。我想更改我的应用程序的语言,为此我使用了在 stackoverflow 上找到的代码:
private void restartActivityInLanguage(String language) {
Locale locale = new Locale(language);
Configuration config = new Configuration();
config.locale = locale;
Resources resources = getResources();
resources.updateConfiguration(config, resources.getDisplayMetrics());
getActivity().recreate();
}
polishLanguage = view.findViewById(R.id.polish_language);
englishLanguage = view.findViewById(R.id.english_language);
polishLanguage.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
restartActivityInLanguage("pl");
}
});
englishLanguage.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
restartActivityInLanguage("en");
}
});
此代码与我的应用程序的主要部分完美配合,但有些地方的文本没有改变,并保持与我的整个手机相同的语言版本,这些地方是:
弹出菜单
holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context wrapper = new ContextThemeWrapper(context, R.style.PopupMenu); PopupMenu popup = new PopupMenu(wrapper, v); popup.inflate(R.menu.browse_location_menu); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.browse_location_edit: onProductClick.onClick(locationModel); break; case R.id.browse_location_delete: onProductClick.onDelete(locationModel); break; default: break; } return true; } }); popup.show(); } });
<item
android:id="@+id/browse_location_edit"
android:title="@string/browse_location_edit" />
<item
android:id="@+id/browse_location_delete"
android:title="@string/browse_location_delete"/>
-tablayout标题
TabLayout tabLayout = findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) ->
{
switch (position) {
case 0:
tab.setText(getString(R.string.add_product));
break;
case 1:
tab.setText(getString(R.string.add_location));
break;
}
}
).attach();
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="@dimen/TabLayoutHeight"
android:background="@color/IvoryBackground"
app:layout_constraintTop_toBottomOf="@+id/toolbar" />
我正在使用 string.xml 文件中的文本,该文件包含两种语言版本的字符串。
对于可能导致此问题的原因,我已经没有想法了。 logcat 中没有错误,只是文本没有改变。任何帮助和建议将不胜感激:)
最佳答案
您可以尝试做一些事情:
首先:您使用的上下文:
getString(R.string.my_string);
getApplication().getString(R.string.my_string);
getApplicationContext().getString(R.string.my_string);
getBaseContext().getString(R.string.my_string);
其二:获取String的方法:
Resources.getSystem().getString(R.string.my_string);
getResources().getString(R.string.my_string);
getString(R.string.my_string);
我前段时间遇到过这个问题,第一种方法对我有用。
关于java - Android 应用程序语言到处都在变化,但在菜单和选项卡布局标题中没有变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65515847/