ActionBar (Support) with Fragment (support)

2019-03-12 10:17发布

问题:

I need to use a combination of action bar and fragments in one of my android applications that targets Gingerbread too. So I have used the action bar from the v7 support library and fragments from the v4 support library and extend my class with FragmentActivity.

I get an error when I type out the line

actionbar = getSupportActionBar();

The error states that getSupportActionBar() is undefined for the type myFragmentClass (my class name). The code works perfectly without the support library. Is there a solution to my problem?

Thanks!

回答1:

You must extend ActionBarActivity instead of FragmentActivity to have Actionbar with fragments.

If you're using the v7 appcompat library, your activity should instead extend ActionBarActivity, which is a subclass of FragmentActivity (for more information, read Adding the Action Bar).

You can find more info at the page given below.The above line is taken from the page below(Last para). http://developer.android.com/training/basics/fragments/creating.html

Edit- This is not a bug. Its just lack of knowledge. Sometimes basic are not clear. I am currently learning, that too from the android website, and that's how I got to give you the answer.



回答2:

write this code in OnAttach() method:

actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();

ActionBarActivity is deprecated. Use

actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();



回答3:

I had also tried using:

actionbar = getActivity().getSupportActionBar();

and it didn't work until I did this:

ActionBar actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar();

So it worked when I cast to my MainActivity.



回答4:

for android.support.v7

ActionBar actionBar =  ((AppCompatActivity) getActivity()).getSupportActionBar();

//than next for example 
actionBar.setDisplayHomeAsUpEnabled(true);


回答5:

To call the ActionBar inside a Fragment use this:

actionbar = getActivity().getSupportActionBar();

A Fragment has no ActionBar but the Activity. That's why you have to call it this way.



回答6:

I have tried it by extending ActionBarActivity and make some changes in AndroidManifest.xml as

 <activity android:name="yourActionbarActivity" 

android:theme="@style/Theme.AppCompat.Light">

and it works fine for me



回答7:

No need to do any changes any where, just use getActionBar().setTitle(title) instead of getSupportActionBar when you use FragmentActivity. It's working fine for me.