Search code examples
androidandroid-fragmentsnavigation-drawerandroid-fragmentactivitybottomnavigationview

android - How to add a NavigationDrawer within an activity that has a BottomNavigationBar with just one Toolbar?


I have a MainActivity contains:

1- BottomNavigationBar and 5 tabs with 5 fragments.

2- main theme NoActionBar.

3- each fragment has a layout with its own Toolbar and different title.

Now i want to add a NavigationDrawer in the MainActivity and only one ActionBar that cantains (the Title of the Fragment of the BottomNavigationBar's tab & the NavDrawer icon button) thats all in one ActionBar. this image is define the issue i have: enter image description here


Solution

  • Well, if you only want to show a title and icon on the fragments toolbars, then there's no need for a toolbar for each fragment. just use the one in the main activivy and change the title and the icon when the tab gets changed.

    using this:

    public class MainActivity extends AppCompatActivity {
    
     public BottomBar bottomBar;
     private Toolbar toolbar;
     private ImageView toolbarIcon;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(" "); 
    
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
              @Override
              public void onTabSelected(@IdRes int tabId) {
    
                switch (tabId) {
                  case R.id.tab1: 
                    TabOne tabOne= new TabOne();
                    commitFragment(tabOne);
                    toolbar.setTitle("Tab One");
                    toolbarIcon.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_tab_1));
                    break;
    
                  case R.id.tab1: 
                    TabTwo tabTwo= new TabTwo ();
                    commitFragment(tabTwo);
                    toolbar.setTitle("Tab Two");
                    toolbarIcon.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_tab_2));
                    break;
    
                   // and so on....
                }
              }
            });
         }
       }
    

    And add an ImageView inside the toolbar to better control the changes.

    <android.support.v7.widget.Toolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      android:background="@color/colorPrimary">
    
      <ImageView
        android:id="@+id/back_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start" 
        android:scaleType="fitXY"/>
    
    </android.support.v7.widget.Toolbar>