Search code examples
androidandroid-fragmentsactionbarsherlockmenuitem

Is it possible to manipulate the action bar from a separate fragment?


I'm relatively new to action bars and I'm using the actionBarSherlock library. I'm aware that actionbar's work best when you have actions that occur often and are easily accessible.

Background:

My action bar currently works by enabling a home button and onCreateOptionsMenu that inflates a menu with a calendar menu item (not visible) and settings menu item.

I have a main activity that calls multiple fragments like FragA, FragB, FragC.

Question:

Is it possibly to somehow manipulate my menu items from my fragments, or at least when they are about to be called in such a way, that I can "show" the calendar menu item and handle calls to it?

Here's what I have so far: actionbar_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:orientation="horizontal" >
<Button
    android:id="@+id/b1"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:text="Stuff" />
</LinearLayout>

Here's how I use the homeButton:

public void onResume() 
{
    super.onResume();

    actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setIcon(R.drawable.icon_tsn);...
}

The fragment I want to work with just extends SherlockFragment.. Any help is appreciated...


Solution

  • Is it possibly to somehow manipulate my menu items from my fragments, or at least when they are about to be called in such a way, that I can "show" the calendar menu item and handle calls to it?

    Your fragment is welcome to call setHasOptionsMenu(true) (e.g., from onCreateView()), at which point it will be called with onCreateOptionsMenu() and onOptionsItemSelected(), much like activities are. If the fragment is visible, its action bar items will appear, otherwise they will be removed.

    Hence, the typical pattern is to have the activity define action bar items that are valid regardless of what fragments are visible, and to have fragments define action bar items that are specific to them.