Thursday, October 8, 2020

Easiest Way to implement the Bottom Navigation Bar using fragments in Android Studio



What is bottom bar?

Bottom bar is used as an alternative to the top toolbar or tabs activity. It allows movement between the primary screens of the application. It generally has three to five destinations each associated with different layout or content. In this article I am going to help you achieve the goal of implementing the bottom bar with the help of fragments.

How to use bottom bar in Andoid studio?


Step 1: Create a new Android Studio project and complete all the further steps.

Step2: Create a new menu resource file by going to res -> new -> Android Resource file name the file and select the resource type as Menu.





Step 3: Make number of menus according to your needs and assign them the icon and the text as shown below

 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto">  
   <item  
     android:id="@+id/id1"  
     android:icon="@drawable/home"  
     android:title="@string/home" />  
   <item  
     android:id="@+id/id2"  
     android:icon="@drawable/authentication"  
     android:title="@string/authentication" />  
   <item  
     android:id="@+id/id3"  
     android:icon="@drawable/discover"  
     android:title="@string/discover"/>  
   <item  
     android:id="@+id/id4"  
     android:icon="@drawable/me"  
     android:title="@string/me" />  
 </menu>  

Step 4: Now in your activity_main.xml file add a bottom navigation view and a frame layout and constraint them as shown below.

 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   <FrameLayout  
     android:id="@+id/parentLayout"  
     android:layout_width="match_parent"  
     android:layout_height="0dp"  
     app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toTopOf="parent"></FrameLayout>  
   <com.google.android.material.bottomnavigation.BottomNavigationView  
     android:id="@+id/bottomNavigationView"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:animateLayoutChanges="false"  
     android:background="@drawable/botton_menu_bg"  
     android:paddingBottom="20dp"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintHorizontal_bias="1.0"  
     app:layout_constraintStart_toStartOf="parent"  
     app:menu="@menu/bottom_nav_menu" />  
 </androidx.constraintlayout.widget.ConstraintLayout>  

Result till now



Step 5: Now Its the time to declare all the four fragments. Go to new -> Fragment -> Blank Fragment and name them as Home, Authentication, Discover, Me. Don't forget to change the text in the xml files of all the four fragments. Otherwise how will we differentiate them?...

Step 6: Navigate to MainActivity.java file and declare all the four fragments there. As shown in the code below.

 public class MainActivity extends AppCompatActivity {  
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   }  
 }  

Step 7: Now we can move towards the declaration and initialization of a  Fragment object, fragment manager and bottom navigation view. The code after performing the tasks looks like this.
Also don't forget to implement BottomNavigationView.OnNavigationItemSelectedListener.

 public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {  
   
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   
   
   
   private Fragment activeFragment = null;  //step 7
   private FragmentManager manager;  //step 7
   BottomNavigationView bottomNavigationView;  //step 7
   
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     bottomNavigationView = findViewById(R.id.bottomNavigationView); //step 7 
       
     setUpBottomNavigation();  //step 7
   
   }  
   
   //bottom navigatio view setup  //step 7
   private void setUpBottomNavigation() {  
     bottomNavigationView.setOnNavigationItemSelectedListener(this);  
     manager = getSupportFragmentManager();  
     activeFragment = home;  
   }  
   
     
   
   @Override  
   public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
     return false;  
   }  
 }  


Step 8: Now add the rest of code to the original code file.


 public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {  
   
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   
   
   
   private Fragment activeFragment = null;  
   private FragmentManager manager;  
   BottomNavigationView bottomNavigationView;  
   
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     bottomNavigationView = findViewById(R.id.bottomNavigationView);  
   
     addAllFragmentOnce();  
     setUpBottomNavigation();  
   }  
   
   
   //bottom navigatio view setup  
   private void setUpBottomNavigation() {  
     bottomNavigationView.setOnNavigationItemSelectedListener(this);  
     manager = getSupportFragmentManager();  
     activeFragment = me;  
   }  
   
   private void addAllFragmentOnce() {  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, activeFragment)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, authentication)  
         .hide(authentication)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, discover)  
         .hide(discover)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, me)  
         .hide(me)  
         .commit();  
   
   }  
   
   //-------show fragment based on selection item id---------------  
   private void showHideFragment(Fragment fragment) {  
     manager.beginTransaction()  
         .hide(activeFragment)  
         .show(fragment)  
         .commit();  
   }  
   
   @Override  
   public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {  
     switch (menuItem.getItemId()) {  
   
       case R.id.id1:  
         clearBackStack();  
         showHideFragment(home);  
         activeFragment = home;  
         break;  
   
       case R.id.id2:  
         clearBackStack();  
         showHideFragment(authentication);  
         activeFragment = authentication;  
         break;  
   
       case R.id.id3:  
         clearBackStack();  
         showHideFragment(discover);  
         activeFragment = discover;  
         break;  
   
       case R.id.id4:  
         clearBackStack();  
         showHideFragment(me);  
         activeFragment = me;  
         break;  
     }  
     return true;  
   }  
   
   //  --------------clear the fragments from the stack-------------------  
   private void clearBackStack() {  
     FragmentManager fm = this.getSupportFragmentManager();  
     for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {  
       fm.popBackStack();  
     }  
   }  

  Don't know what's happeing ?No worries,First have a look at this and try to understand then I will explain what's happening here.

Okay Let me explain now.
After initialising and declaration I added all the fragments to the transition list in the method addAllFragmentAtOnce() and displayed only first one i.e active fragment, all others transition are hidden.

In the method setUpBottomNavigation() I set up a onItemClick listener and initially set home as the active fragment.

onNavigationItemSelected() method is called when the navigation item is clicked and based on the id of the items it displays and hide the fragments using the method clearBackStack() and showHideFragment();

Cheers! You successfully implemented the bottom navigation with the help of fragments.


Conclusion 

You just learned how you can use fragments and implement bottom navigation bar in an android application using Android Studio. However, if you think you need this at any later time consider bookmarking this.

If you have any questions you can ask me in the comment section.
Latest
Next Post

post written by:

Hi, Navjyot Singh is a coder, content maker and a freelance developer who's pursuing an undergraduate Engineering degree in Computer Science. He started out as a web developer but later picked up the mobile as his favourite platform to develop applications. A Writer by day and coder by night is loathed to discuss himself as the third person but can be persuaded to do so from time to time.

0 comments: