Adding items to action bar (using ActionBarSherlock)

瘦欲@ 提交于 2019-12-11 04:59:36

问题


I'm using ActionBarSherlock in my project and sometimes need to add one or more items inside the action bar.

At this BaixadosFragment class (that extends SherlockFragment), I'm using the following code and it works fine:

@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater)
{
    inflater.inflate(R.menu.main, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.refresh:
            refresh();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

In this case, I'm adding a refresh button, witch is lonely inside main.xml

BUT I want to do the same at CupomDetalheActivity (though adding a share button), witch extends SherlockFragmentActivity instead. So I'm not able to override "onCreateOptionsMenu" as it has a different signature (below):

//this is inside SherlockFragmentActivity
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
    return true;
}
//this is inside SherlockFragment
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //Nothing to see here.
}

Whith SherlockFragmentActivity, I don't even see where can I use the inflater to bring up the xml containing the share button... I appreciate a lot any ideas and suggestions...

[EDIT] This worked, according to DroidT's suggestion:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.share, menu);
    super.onCreateOptionsMenu(menu);
    return true;
}

回答1:


Your SherlockFragmentActivity also has an onCreateOptionsMenu() and onPrepareOptionsMenu(). You can inflate your menu options in the onCreateOptionsMenu() by using getSupportMenuInflater(). You would want to make a call to invalidateOptionsMenu() in your SherlockFragmentActivity whenever you want the change to happen and add the menu options in onPrepareOptionsMenu(). For more information look at the "Changing menu items at runtime" section of this link.




回答2:


If you are using a menu inside of a fragment, make sure you call setHasOptionsMenu(true); in the fragments onCreate(Bundle savedInstance) method



来源:https://stackoverflow.com/questions/19013294/adding-items-to-action-bar-using-actionbarsherlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!