Antonio Carelli
Antonio Carelli

Reputation: 53

How access ActionBar from fragment on Android

On my application I have only one activity (that extends ActionBarActivity ) and various Fragments (that extends Fragment). When the user click on a menu option, the application change the Fragment. At this moment I want to change de title and the background color of the ActionBar. When I try ActionBar actionBar = getActivity().getActionBar(); I got a null exception.

I'm using support library, and on the Activity I'm using android.support.v7.app.ActionBar actionBar = getSupportActionBar(); successfully.

On the Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.material_cadastro, container, false);

    viewHolder = new MaterialViewHolder(view);

    ActionBar actionBar = getActivity().getActionBar();
    actionBar.setTitle(R.string.inserir_material);

    return view;
}

Debuging I got that the Activity is returning OK, but the ActionBar is null:

getActivity() = {br.com.americocarelli.vendasfacil.ui.MenuPrincipal@3b56766f}
getActivity().getActionBar() = null

Upvotes: 0

Views: 3190

Answers (3)

SilentKnight
SilentKnight

Reputation: 14021

Override your onAttach(Activity), then cast your Activity to ActionBarActivity, the you can get an ActionBar. Like:

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    ActionBar actionBar=((ActionBarActivity)activity).getSupportActionBar();
}

Upvotes: 3

dominik4142
dominik4142

Reputation: 576

You are probably building it with build tools >=21, that versions causes activity.getActionBar() returns null, you should use getSupportActionBar() instead. EDIT: if you get NPE at exactly this line: getActivity(). ... then you are probably referencing it before or after fragment is attached to activity. Could you please paste the context (place, in what function) you are using it?

Upvotes: 0

hfann
hfann

Reputation: 599

Since you use the support library (ActionBarActivity), then use ((ActionBarActivity)getActivity()).getSupportActionBar(); to get access to the support action bar.

Upvotes: 1

Related Questions