Android

[Android] 다중언어 설정 (feat. Java)

김한토 2024. 11. 11. 15:38
반응형
SMALL

https://velog.io/@charon/Android-%EC%96%B8%EC%96%B4-%EC%84%A4%EC%A0%95

 

 

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

private void changeLanguage(String languageCode) {
        try {
            Locale locale = new Locale(languageCode);
            Locale.setDefault(locale);

            Configuration config = new Configuration();
            config.setLocale(locale);

            Constants.SELECTED_LANGUAGE_LOCALE = locale;

            getResources().updateConfiguration(config, getResources().getDisplayMetrics());

        } catch (Exception e) {
            Log.e(TAG, "Language change failed", e);
        }
    }

    public void refreshLanguage(String languageCode) {
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.custom_dialog, null);

        TextView dialogMessage = dialogView.findViewById(R.id.dialog_message);
        dialogMessage.setText(getResources().getString(R.string.change_language));

        alert = new AlertDialog.Builder(getActivity())
                .setView(dialogView)
                .create();

        Button positiveButton = dialogView.findViewById(R.id.positive_button);
        positiveButton.setOnClickListener(view -> {
            changeLanguage(languageCode);

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(CURRENT_LANGUAGE, languageCode);
            editor.apply();



            FragmentManager fragmentManager = getActivity().getFragmentManager();
            HomeFragment homeFragment = new HomeFragment();
            fragmentManager.beginTransaction()
                    .replace(R.id.fragment_home, homeFragment)
                    .commit();

            dismiss();

            alert.dismiss();
        });

        Button negativeButton = dialogView.findViewById(R.id.negative_button);
        negativeButton.setOnClickListener(v -> alert.dismiss());

        if (alert.getWindow() != null) {
            alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        }

        alert.getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        alert.show();
    }

 

설정 언어 값 바꾸면 sharedPref에 저장 한뒤, 앱이 시작되면 BASEACTIVITY에서 해당 locale값을 설정한다. (위에 링크 참조. )

 

그리고 모든 activity마다 baseAvtivity를 상속 받게 한다. (attach)

반응형
LIST