Search code examples
androidandroid-fragmentsandroid-activityandroid-toolbar

Stop toolbar from Activity getting displayed in Fragments


My activity's current layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <include
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/main_toolbar"
        layout="@layout/main_toolbar"/>

    <FrameLayout
        android:id="@+id/flMainContainer"
        android:layout_below="@id/main_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/header"/>


</android.support.v4.widget.DrawerLayout>

So it is essentially just a toolbar and a FrameLayout (which is a container thats populated by Fragments). Because of this, every fragment ends up having this toolbar, which I only want in the MainActivity. How do I get around this? Some Fragments have their own toolbar, but because only the FrameLayout in the activity gets replaced by the fragment's layout, the activity's toolbar is always there.

If I give a fragment it's own toolbar, the activity's toolbar will still be displayed above the fragment's toolbar - I want it to replace the toolbar instead.

In my AndroidManifest I've set my theme to be NoActionBar.

Appreciate any help!


Solution

  • In your first fragment in onViewCreated(..) use this :-

     if (getActivity()!=null) 
          getActivity().findViewById(R.id.main_toolbar).setVisibility(View.GONE);