Android 自切换语言

void changeLanguage(){
        final String[] cities = {getString(R.string.lan_chinese),getString(R.string.lan_en)};
        final String[] locals = {"zh", "en"};
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
        builder.setItems(cities, new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
                if(!locals[which].equals(StoreUtils.getLanguageLocal(SettingsActivity.this))) {
                    StoreUtils.setLanguageLocal(SettingsActivity.this, locals[which]);
                    EventBus.getDefault().post("EVENT_REFRESH_LANGUAGE");
                }else {
                    Toast.makeText(SettingsActivity.this,getString(R.string.cant_change_language),Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }

在Activity中:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        Log.e("TAG","注册EventBus");
        changeAppLanguage();
    }

@Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        gcAndFinalize();
    }

 public void changeAppLanguage() {
        String sta = StoreUtils.getLanguageLocal(this);
        if(sta != null && !"".equals(sta)){
            // 本地语言设置
            Locale myLocale = new Locale(sta);
            Log.e("TAG",sta+" "+myLocale.getDisplayLanguage(myLocale));
            Resources res = getResources();
            DisplayMetrics dm = res.getDisplayMetrics();
            Configuration conf = res.getConfiguration();
            conf.setLocale(myLocale);
            res.updateConfiguration(conf, dm);
        }

    }

你可能感兴趣的:(Android 自切换语言)