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.
While this question has an accepted answer already, I must point out that it isn't totally correct: calling
getSupportActionBar()
fromFragment.onAttach()
will cause aNullPointerException
when the activity is rotated.Short answer:
Use
((ActionBarActivity)getActivity()).getSupportActionBar()
inonActivityCreated()
(or any point afterwards in its lifecycle) instead ofonAttach()
.Long answer:
The reason is that if an
ActionBarActivity
is recreated after a rotation, it will restore all Fragments before actually creating theActionBar
object.Source code for
ActionBarActivity
in thesupport-v7
library:ActionBarActivityDelegate.createDelegate()
creates themImpl
object depending on the Android version.super.onCreate()
isFragmentActivity.onCreate()
, which restores any previous fragments after a rotation (FragmentManagerImpl.dispatchCreate()
, &c).mImpl.onCreate(savedInstanceState)
isActionBarActivityDelegate.onCreate()
, which reads themHasActionBar
variable from the window style.mHasActionBar
is true,getSupportActionBar()
will always returnnull
.Source for
ActionBarActivityDelegate.getSupportActionBar()
:If someone uses com.android.support:appcompat-v7: and AppCompatActivity as activity then this will work
As an updated answer for Pierre-Antoine LaFayette's answer
ActionBarActivity is deprecated; use
AppCompatActivity
insteadin your
fragment.xml
addToolbar
Tag from support libraryNow how we can control it from
MyFragment
class? let's seeinside
onCreateView
function add the followingand if you want to add
items
to the toolbar withinMyFragment
youmust
add this line insideonCreateView
functionthis line is important, if you forget it, android will not populate your menu Items.
assume we identify them in
menu/fragment_menu.xml
after that override the following functions
hope this helps
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().
You do need the cast. It's not poor design, it's backwards compatibility.