首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >android studio切换语言无限重载应用

android studio切换语言无限重载应用
EN

Stack Overflow用户
提问于 2021-05-31 18:38:16
回答 1查看 30关注 0票数 0

我是一个完全的初学者在android studio与java。我已经创建了一个导航抽屉,其中的主页有一个旋转器来选择应用程序语言。当语言发生变化时,应用程序会重新加载并成功应用语言变化。问题是,我创建视图的方式,应用程序在加载的瞬间就会无限地重新加载,而不需要我更改语言。因此,我需要一种方法来告诉它,只有当我点击不同的语言时才重新加载我的应用程序。

我的代码:

代码语言:javascript
复制
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 
    }


}

我将非常感谢你的帮助

EN

回答 1

Stack Overflow用户

发布于 2021-05-31 18:52:37

你可以得到一个回调,当配置更改的活动,如方向,地区等…

在活动中重写onConfigurationChanged方法

代码语言:javascript
复制
@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"中声明

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67772184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档