How can I hide the actionbar in a single fragment?

2019-08-28 06:14发布

问题:

I am using AppCompat for my theme in my app. Also, I am using a viewpager to manage some fragments. Now I would to hide the actionbar in one of my fragments. How can I do that. I tried to hide the actionbar manually in the fragment like this

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActionBarActivity activity = (ActionBarActivity) this.getActivity();
    ActionBar aBar = activity.getSupportActionBar();
    aBar.hide();
}

but this hides the actionbar for all fragments. Any ideas?

回答1:

When you load other fragments call (for example in onResume):

aBar.show();

Edit:

in each fragment that you want to have show the ActionBar put the following method:

@Override
public void onResume() {
    super.onResume();
    aBar.show();
}

in the OnResume method of the Fragment which you don't want the action bar to show do this:

@Override
public void onResume() {
    super.onResume();
    aBar.hide();
}

SInce you're using the view pager I assume you're using code similar to:

http://developer.android.com/reference/android/support/v4/view/ViewPager.html

In which case in this method:

@Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                    // add check here to determine if the selected item is the fragment you want     to hide the action bar in... 
                    // if so call aBar.hide();
                      // for example:

                    if(i == MY_NO_BAR_FRAGMENT) {
                          // when you set up the view fragment, you would set MY_NO_BAR_FRAGMENT to the index of that fragment in the view pagers list of pages.
                          aBar.hide();
                    }
                }
            }
        }