We can access the action bar from a fragment and make customizations to aid the user on a per-fragment basis. Items can be added, and you can also customize the up navigation, keeping a consistent structure with the rest of the app.
When a fragment is added to the activity, we can allow that fragment to add items to the action bar. This is similar to providing items from the activity. Let's take a look at the following steps:
public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetHasOptionsMenu(true); }
menu
resource folder:<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_share" android:icon="@android:drawable/ic_menu_share" yourapp:showAsAction="ifRoom" android:title="@string/action_share" /> </menu>
OnCreateOptionsMenu()
method of the fragment:public override void OnCreateOptionsMenu( IMenu menu, MenuInflater inflater) { inflater.Inflate(Resource.Menu.ActionBarItems, menu); }
Another thing we may want to do is to make the home button in the action bar and change to an up button when we navigate down to a fragment:
private void OnBackStackChanged() { bool hasBack = SupportFragmentManager.BackStackEntryCount > 0; SupportActionBar.SetDisplayHomeAsUpEnabled(hasBack); }
protected override void OnCreate(Bundle bundle) { ... SupportFragmentManager.BackStackChanged += delegate { OnBackStackChanged(); }; OnBackStackChanged(); }
public override bool OnSupportNavigateUp() { SupportFragmentManager.PopBackStack(); return true; }
If a fragment wants to place items on the action bar, we have to let the activity know. The way we do this is by setting the HasOptionsMenu
property to true
, or on Android versions 3.0 and above, by passing true
to the SetHasOptionsMenu()
method.
We can then go ahead and create and inflate the menu structure in the same manner as if we were adding an options menu to an activity. There is an OnCreateOptionsMenu()
method in the fragment that performs the same function as the method on the activity.
Another useful thing for us to do is to make the home button into an up button after we navigate to a child fragment. This is simple to add by subscribing to the BackStackChanged
event on the fragment manager. In this event, we can check to see if there is anything on the back stack and update the home button.
After adding the up arrow to the home button, we can override the OnSupportNavigateUp()
method or the OnNavigateUp()
method to pop the back stack of the fragment manager.