Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the ActionBar from within a Fragment

How do you access the ActionBar from within a Fragment (android.support.v4.app.Fragment). I am using the Android Support Library v4 and v7. I'm not using the Sherlock library's.

The activity hosting the fragment is an ActionBarActivity.

I have read the Android help section Fragment which led me too getActivity() but there is no getSupportActionBar() method.

ActionBar actionBar = getActivity().getSupportActionBar()
like image 631
Reafidy Avatar asked Aug 06 '13 21:08

Reafidy


2 Answers

If you are using AppCompatActivity then do it like this.
((AppCompatActivity )getActivity()).getSupportActionBar();

Also it is advised to shift to Toolbar with AppCompatActivity instead of action bar(app bar). For more details refer this http://android-developers.blogspot.in/2014/10/appcompat-v21-material-design-for-pre.html

like image 66
Mightian Avatar answered Sep 28 '22 19:09

Mightian


I have read the Android help section Fragment which led me too getActivity() but there is no getSupportActionBar() method.

You will need to cast the result of getActivity() to be an ActionBarActivity, on which you will find getSupportActionBar().

like image 22
CommonsWare Avatar answered Sep 28 '22 21:09

CommonsWare