代码之家  ›  专栏  ›  技术社区  ›  Darksymphony

设置选项菜单项的标题

  •  0
  • Darksymphony  · 技术社区  · 7 年前

    我正在为多种语言创建一个应用程序。除了“选项”菜单外,语言切换效果良好。

    我的菜单里有这个。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" />
    

    这导致我的meni项目始终具有相同的标题,甚至我切换了语言,因为它从XML获取。

    现在,我尝试在MainActivity中以编程方式进行更改。java with item。集合标题:

        @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);
        }
    }
    

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

    3 回复  |  直到 7 年前
        1
  •  1
  •   shmakova    7 年前

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

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem settings = menu.findItem(R.id.action_settings);
        // do smth with menu item
        return true;
    }
    
        2
  •  0
  •   Tung Tran    7 年前

    其他方式,你可以打电话 this.recreate(); 切换语言后

        3
  •  0
  •   ehsan khormali    7 年前

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