getSupportActionBar from inside of Fragment ActionBarCompat

Paul picture Paul · Aug 19, 2013 · Viewed 92.7k times · Source

I'm starting a new project that uses the AppCompat/ActionBarCompat in v7 support library. I'm trying to figure out how to use the getSupportActionBar from within a fragment. My activity that hosts the fragment extends ActionBarActivity, but I don't see a similar support class for Fragments.

From within my fragment

    public class CrimeFragment extends Fragment {
          //...

          getActivity().getSupportActionBar().setSubtitle(R.string.subtitle); // getSupportActionBar is not defined in the v4 version of Fragment

          //...
    }

The google page for using it (http://android-developers.blogspot.in/2013/08/actionbarcompat-and-io-2013-app-source.html) says there should be no changes for the v4 fragment. Do I need to cast all my getActivity() calls to an ActionBarActivity? That seems like poor design.

Answer

Pierre-Antoine LaFayette picture Pierre-Antoine LaFayette · Aug 19, 2013

After Fragment.onActivityCreated(...) you'll have a valid activity accessible through getActivity().

You'll need to cast it to an ActionBarActivity then make the call to getSupportActionBar().

((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle(R.string.subtitle);

You do need the cast. It's not poor design, it's backwards compatibility.