我是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
}
}
我将感谢你的帮助
当配置在"活动"(如方向、区域设置等(中发生更改时,您可以获得回调
覆盖活动中的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"
中声明