我是一个完全的初学者在android studio与java。我已经创建了一个导航抽屉,其中的主页有一个旋转器来选择应用程序语言。当语言发生变化时,应用程序会重新加载并成功应用语言变化。问题是,我创建视图的方式,应用程序在加载的瞬间就会无限地重新加载,而不需要我更改语言。因此,我需要一种方法来告诉它,只有当我点击不同的语言时才重新加载我的应用程序。
我的代码:
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
Spinner spinner = root.findViewById(R.id.spinner);
ImageView flags = (ImageView) root.findViewById(R.id.flag);
spinner.setAdapter(new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_spinner_dropdown_item,
CountryData.countryNames));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
flags.setImageResource(CountryData.countryFlag[spinner.getSelectedItemPosition()]);
String selectedLang = parent.getItemAtPosition(position).toString();
if(selectedLang.equals("GR")){
setLocal(HomeFragment.this,"el"); //app always reloads
}else {
setLocal(HomeFragment.this,"en"); //app always reloads
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
public void setLocal(HomeFragment activity , String langCode){
Locale locale = new Locale(langCode);
locale.setDefault(locale);
Resources resources = activity.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
resources.updateConfiguration(config,resources.getDisplayMetrics());
getActivity().recreate(); //app reloads
}
}我将非常感谢你的帮助
发布于 2021-05-31 18:52:37
你可以得到一个回调,当配置更改的活动,如方向,地区等…
在活动中重写onConfigurationChanged方法
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// here you can update UI
//Checks the current language
if (newConfig.locale == Locale.ENGLISH) {
}
}必须在清单android:configChanges="locale"中声明
https://stackoverflow.com/questions/67772184
复制相似问题