【问题标题】:Android - Support Multilanguage app in a ViewPagerAndroid - 在 ViewPager 中支持多语言应用程序
【发布时间】:2015-05-05 22:36:12
【问题描述】:

我有一个带有 FragmentPagerAdapter 的 ViewPager 和五个从我的 MainActivity 调用的选项卡。我想动态更改我的应用程序的语言。为此,我将我的语言偏好保存在我的onSavedInstanceState 中,如下所示:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String predefined_lang = prefs.getString(LANGUAGES, "error");
    String sub_lan = predefined_lang.substring(0,2).toLowerCase();
    outState.putString(LANG, sub_lan);
    System.out.println(">>saveinstance"+predefined_lang);
}

然后我从onRestoreInstanceState检索语言:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    Configuration configuration = getResources().getConfiguration();
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    //System.out.println(savedInstanceState.getString(LANG));

    //configuration.locale = new Locale(savedInstanceState.getString(LANG));
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String predefined_lang = prefs.getString(LANGUAGES, "error");
    String sub_lan = predefined_lang.substring(0,2).toLowerCase();
    configuration.locale = new Locale(savedInstanceState.getString(LANG));
    getResources().updateConfiguration(configuration, displayMetrics);
    System.out.println(">>onrestore"+savedInstanceState.getString(LANG));

}

所以我尽量避免选择的语言不会在设备的默认语言中再次更改。 实际上,所有字符串资源都以正确的语言显示,除了 viewPager 的选项卡名称。例如:

我有这五个标签:

| tab1 -|- tab2 -|- tab3 -|- tab4 -|- tab5 |

如果手机的默认语言是Italian,但我选择在English 中显示应用程序,那么一切都是用英文写的,甚至是选项卡的名称。但是当我旋转屏幕时,除了选项卡的名称之外,所有内容都用英语书写,而是用意大利语书写。解决方案?

【问题讨论】:

  • 只有旋转手机才有问题?
  • 是的,只有在屏幕旋转时...

标签: android android-viewpager locale multilingual screen-rotation


【解决方案1】:

当方向改变时,您可以通过添加到清单中来停止重新加载应用程序:

<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize">
</activity>

到你的 MainActivity:

 public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){

    }
}

或者您可以指定任何其他操作,详细了解运行时更改:http://developer.android.com/guide/topics/resources/runtime-changes.html

希望对你有帮助

【讨论】:

  • 在我的清单中已经出现了这行代码:android:configChanges="orientation|locale" ...
  • 这样就可以了,你把其他代码放在你的MainActivity中关于方向了吗?
  • 好的,非常感谢!我删除了onSavedInstanceStateonRestoreInstanceState 方法,而不是这些我添加了onConfigurationChanged 方法,我检查newConfig.locale 是否等于我想要的语言环境,现在它就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多