Search code examples
javaandroidandroid-actionbarandroid-fragmentactivity

Removing Action Bar completely from Fragment


I am currently trying to change the way an application looks.

The application uses 3 fragments that can be called base on network state changes. The fragments are all set to landscape, this leads the action bar to be a huge portion of the screen. I am trying to find a way to removed the action bar completely and allow the layout to expand to the entirety of the screen.

I have already tried things like:

getActionBar().hide();

Theme Changes

setSystemUiVisibility();

These option will either create a large bar across the screen where it should be or just display the Action bar anyways.

I assume this is something with the way fragments work that I just do not understand.


Solution

  • If you want to completely remove the ActionBar (AppBar) completely from your App, then follow these steps:

    • Go to your AndroidManifest.xml
    • Edit this line: android:theme="@style/{theme}"> to android:theme="@style/Theme.AppCompat.Light.NoActionBar"> or anything that ends with NoActionBar.

    And if you want to remove the ActionBar just from your Fragment, then add next code in the onCreateView() of the Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        // create ContextThemeWrapper from the original Activity Context with the custom theme
        final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);
    
        // clone the inflater using the ContextThemeWrapper
        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
    
        // inflate the layout using the cloned inflater, not default inflater
        return localInflater.inflate(R.layout.yourLayout, container, false);
    }
    

    Or if you want to remove the ActionBar from an Activity, add this one line of code to the onCreate() method of the Activity.

    setTheme(R.style.{your style}

    Remember

    • The {style} should end with NoActionBar
    • And most importantly, add the code before these two lines of code (add it to the top of the method):

      super.onCreate(savedInstanceState);
      setContentView(R.layout.{your layout});
      

    Hope this answer helped!