msSelected或onCreateOptionsMenu之外

msSelected或onCreateOptionsMenu之外

本文介绍了Android的 - 如何动态onOptionsItemsSelected或onCreateOptionsMenu之外更改菜单项的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从onOptionsItemSelected(菜单项项)的方法之外更改菜单项的标题。

I'm trying to change the title of a menu item from outside of the onOptionsItemSelected(MenuItem item) method.

我已经做了以下内容:

public boolean onOptionsItemSelected(MenuItem item){
    try{
        switch(item.getItemId()){
            case R.id.bedSwitch:
                if(item.getTitle().equals("Set to 'In bed'")){
                    item.setTitle("Set to 'Out of bed'");
                    inBed = false;
                }else{
                    item.setTitle("Set to 'In bed'");
                    inBed = true;
                }
                break;
        }
    } catch(Exception e){
        Log.i("Sleep Recorder", e.toString());
    }
    return true;
}

不过,我希望能够修改一个特定的菜单项的标题这种方法之外

however i'd like to be able to modify the title of a particular menu item outside of this method

在此先感谢您的帮助

刘德华

推荐答案

我会建议保持活动中引用你的onCreateOptionsMenu然后使用该检索要求变化的菜单项,当你需要它。例如,你可以做沿着以下线的东西:

I would suggest keeping a reference within the activity to the Menu object you receive in onCreateOptionsMenu and then using that to retrieve the MenuItem that requires the change as and when you need it. For example, you could do something along the lines of the following:

public class YourActivity extends Activity {

    private Menu menu;
    private String inBedMenuTitle = "Set to 'In bed'";
    private String outOfBedMenuTitle = "Set to 'Out of bed'";
    private boolean inBed = false;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // Create your menu...

        this.menu = menu;
        return true;
    }

    private void updateMenuTitles() {
        MenuItem bedMenuItem = menu.findItem(R.id.bedSwitch);
        if (inBed) {
            bedMenuItem.setTitle(outOfBedMenuTitle);
        } else {
            bedMenuItem.setTitle(inBedMenuTitle);
        }
    }

}

另外,你可以覆盖<一个href="http://developer.android.com/reference/android/app/Activity.html#on$p$ppareOptionsMenu%28android.view.Menu%29">on$p$ppareOptionsMenu显示菜单每次更新菜单项。

Alternatively, you can override onPrepareOptionsMenu to update the menu items each time the menu is displayed.

这篇关于Android的 - 如何动态onOptionsItemsSelected或onCreateOptionsMenu之外更改菜单项的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:05