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
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();
}