【问题标题】:set title for options menu items设置选项菜单项的标题
【发布时间】:2018-08-12 11:17:08
【问题描述】:

我正在为多种语言创建应用程序。语言切换效果很好,除了选项菜单。

我的 menu/main.xml 中有这个:

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
>

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

<item
    android:id="@+id/action_about"
    android:orderInCategory="100"
    android:title="@string/action_about"
    app:showAsAction="never" />

这导致我的菜单项总是具有相同的标题,即使我切换了语言,因为它从 XML 中获取。

现在我尝试使用 item.setTitle 在 MainActivity.java 中以编程方式进行更改:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Context context = LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
            Resources resources = context.getResources();
            item.setTitle(resources.getString(R.string.action_settings));
            Intent i = new Intent(this,LanguageChange.class);
            this.startActivity(i);
            return true;
        case R.id.action_about:
            Context context = LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
            Resources resources = context.getResources();
            item.setTitle(resources.getString(R.string.about_settings));
            Intent ix = new Intent(this,About.class);
            this.startActivity(ix);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

问题是,菜单项的标题只有在我进入菜单并返回后才会改变。然后更改项目标题。但我需要立即更改它们。

【问题讨论】:

    标签: android menu options


    【解决方案1】:

    我认为标准和最好的方法是翻译您的字符串资源并更改整个应用程序的语言环境

    【讨论】:

      【解决方案2】:

      其他方式,切换语言后拨打this.recreate();

      【讨论】:

        【解决方案3】:

        像这样更改onPrepareOptionsMenu(Menu menu) 中的项目:

        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            MenuItem settings = menu.findItem(R.id.action_settings);
            // do smth with menu item
            return true;
        }
        

        【讨论】:

        • 优秀的答案,正是我需要的。它工作正常!谢谢。
        猜你喜欢
        • 1970-01-01
        • 2017-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多