u3l
u3l

Reputation: 3412

Changing Action Bar items and title on adding Fragments

Let's say I have a FragmentA visible.

I add a FragmentB (keyword: add, not replace), add it to the Fragment back stack and commit.

The issues I'm having doing this is:

1) The action buttons of the action menu of FragmentB are added, but those of FragmentA are not removed.

2) The title of the ActionBar does not change (despite calling getActivity().setTitle("FragmentB") in onResume() of FragmentB.

I can resolve both of these by calling replace instead of add when showing FragmentB however, for quite a few reasons I specifically need to add the Fragment instead (one of them being, I need to retain the state of FragmentA while showing B).

So how would I go about updating the ActionBar correctly as described?

Upvotes: 1

Views: 67

Answers (2)

Ashish Jaiswal
Ashish Jaiswal

Reputation: 804

Try this piece of code:

getActivity().getActionBar().setTitle("FragmentB");

Upvotes: 1

SureshCS50
SureshCS50

Reputation: 3768

Use this code in your Activity.. (for setting title to your fragment).

public void setActionBarTitle(String title) {
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(title);
}

from your fragment onResume(), call this using

// Set title bar
((MyActivity) getActivity())
            .setActionBarTitle("Fragment A");

and in each fragment you need to override onCreateOptionsMenu() to load your menus of that fragment.

Upvotes: 0

Related Questions