Reafidy
Reafidy

Reputation: 8481

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

Upvotes: 12

Views: 8801

Answers (2)

Aniruddha K.M
Aniruddha K.M

Reputation: 7521

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

Upvotes: 9

CommonsWare
CommonsWare

Reputation: 1007624

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().

Upvotes: 27

Related Questions