androidmultiple-languages

How to create multiple language in other activity?


In other question i have answer to create multiple language. But not used in all activity/pages aplications. How to change language in other activity/page?

i have code to main activity/page only, how to create in other activity/page?

i use this code to change language:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LocaleHelper.onAttach(newBase, "en"));
}

private void updateView(String lang) {
    Context context = LocaleHelper.setLocale(this, lang);
    Resources resources = context.getResources();

    navigation_view.getMenu().findItem(R.id.account).setTitle(resources.getString(R.string.menuAccount));
    navigation_view.getMenu().findItem(R.id.settingPassword).setTitle(resources.getString(R.string.menuSettingPass));
    navigation_view.getMenu().findItem(R.id.about).setTitle(resources.getString(R.string.menuAbout));
    navigation_view.getMenu().findItem(R.id.logout).setTitle(resources.getString(R.string.menuLogout));
    navigation_view.getMenu().findItem(R.id.login).setTitle(resources.getString(R.string.menuLogin));
}

and i use this triger to change language:

Paper.book().write("language", "id");
updateView((String)Paper.book().read("language"));
navigation_view.getMenu().findItem(R.id.language_in).setVisible(false);
navigation_view.getMenu().findItem(R.id.language_en).setVisible(true);

source code from : source code full from EDMT Dev


Solution

  • Put your string resources in different folders:

    System will automatically loads proper string resource based on your locale. You need to have attachBaseContext method in all your activities. For cleaner code, you can create a BaseActivity class with attachBaseContext method and extend all your activities from this base class:

    public class BaseActivity extends Activity {
        @Override
        protected void attachBaseContext(Context newBase) {
            super.attachBaseContext(LocaleHelper.onAttach(newBase, "en"));
        }
        // ...
    }
    
    public class MyActivity extends BaseActivity {
        // ...
        private void updateView(String lang) {
            // all your code
        }
    }