How to Create Fragment Using Bottom Navigation in Social Media Android App?
This is the Part 2 of “Build a Social Media App in Android Studio” tutorial, and we are going to cover the following functionalities in this article:
- We are going to Create Bottom Navigation with 5 Fragments (Home, Users, AddBlog, ChatList, Profile).
- On HomeFragment we will be Showing all the added blogs.
- In the UsersFragment, we will be showing all the Registered Users.
- In the AddBlogFragment We will be adding our blogs.
- In the ChatlistFragment we will be showing a chat list of all users with whom we have chat.
- In the ProfileFragment We will be showing the Profile of the user where we will be showing users’ data and the blogs written by the user.
Step By Step Implementation
Step 1: Firstly we will create a menu directory inside the res folder. Refer to this article How to Create Menu Folder & Menu File in Android Studio. And name the menus file as menu_nav.xml for creating the layout of bottom navigation. Below is the code for the menu_nav.xml file.
Step 2: Add dependency to build.gradle (Module: app)
Navigate to the Gradle Scripts > build. gradle(Module: app) and add the below dependency in the dependencies section.
Step 3: Working with the activity_dashboard.xml file
This page will be the first activity in our app after the user logged in. Navigate to the app > res > layout > activity_dashboard.xml and add the below code to that file. Below is the code for the activity_dashboard.xml file.
Step 4: Create 5 new blank fragments
Go to the app(right-click) > New > Fragment > Fragment (Blank) and name the fragment as HomeFragment, ProfileFragment, UsersFragment, ChatListFragment, and AddBlogsFragment.
Step 5: Working with the DashboardActivity.java file
In this file, we are just showing the fragment according to the navigation item selected. Then we will be showing the respective fragment.
HomeFragment fragment=new HomeFragment(); FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content,fragment,""); fragmentTransaction.commit();
Go to the DashboardActivity.java file and refer to the following code. Below is the code for the DashboardActivity.java file.
For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing
Below is the file structure after performing these operations: