home top ad

how to implement to different different tablayout in different different fragment class with viewPager and NavigationView in android studio

Hello friends, tab layout has started to be used a lot today because if we want to make many files look different, then we have to use Tablayout.In this article, we will learn about how to add different different tablayout in different different fragment class with viewPager in an app. TabLayout provides a horizontal layout to display tabs. If TabLayout is used then along with it, Fragment is also used, because fragments are light weight and the app can have more functionality on a single screen if more fragments are added.

if you also want to show tablayout in your application, then follow this code.

Start a New Android Project

Start by creating a new Android project in Android studio. Choose "File", "New", select "New Project" and then click "Next". In the New Android Application window, enter your chosen Application, Project, and Package names and then choose "Next" and last finish. After creating the project, you will see two files, first activity_main and second MainActivity.java, then you have to paste the code given below activity_main and MainActivity.java. After creating the project the first thing you can do is to see that in Gradle Scripts there is a library implementation 'com.google.android.material: material: 1.3.0' for design in build.gradle if not Add the dependency below to your build.gradle and hit the Sync Now button .

1:    implementation 'com.google.android.material:material:1.3.0'  
After the project is created you will see two files activity_main.xml and MainActivity.java Then you just have to paste the code below in order.

Activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:fitsSystemWindows="true"  
   android:orientation="vertical"  
   tools:context=".MainActivity"  
   tools:openDrawer="start">  
   <include  
     layout="@layout/app_bar_main"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent" />  
   <com.google.android.material.navigation.NavigationView  
     android:id="@+id/navi"  
     android:layout_width="wrap_content"  
     android:layout_height="match_parent"  
     android:layout_gravity="start"  
     android:fitsSystemWindows="true"  
     app:itemTextColor="@color/black"  
     app:headerLayout="@layout/nav_header"  
     app:menu="@menu/nav_drawer" />  
 </androidx.drawerlayout.widget.DrawerLayout>  
After pasting this code you will see some error. To fix this error of app_bar_main nav_header and nav_drawer, you have to right click on the layout folder, you will click on the new then layout resource file and you will like this picture app_bar_main and Nav_header will create the layout and to create nav_drawer you have to right click on the res folder, click on the new >> Android resource directory, you will see a list when you click on the directory type, in that list you will see a menu. We will select it and press ok, in this way our menu folder will be created.Finally, by right-clicking on the menu folder, we will create a menu layout by clicking on the menu resource file.

app_bar_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/coordinator_layout"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   <com.google.android.material.appbar.AppBarLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:background="@color/purple_500"  
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
     app:elevation="0dp">  
     <androidx.appcompat.widget.Toolbar  
       android:id="@+id/toolbarmain"  
       android:layout_width="match_parent"  
       android:layout_height="?attr/actionBarSize"  
       app:popupTheme="@style/ThemeOverlay.AppCompat.ActionBar" />  
   </com.google.android.material.appbar.AppBarLayout>  
   <FrameLayout  
     android:id="@+id/framelayout"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     app:layout_behavior="@string/appbar_scrolling_view_behavior" />  
 </androidx.coordinatorlayout.widget.CoordinatorLayout>  
nav_header.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="150dp"  
   android:background="@color/purple_700">  
   <ImageView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="30dp"  
     android:layout_marginStart="20dp"  
     android:src="@mipmap/ic_launcher"  
     android:layout_marginLeft="20dp" />  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentBottom="true"  
     android:layout_marginStart="10dp"  
     android:layout_marginBottom="18dp"  
     android:text="@string/app_name"  
     android:textColor="#F6F3F4"  
     android:textSize="20sp"  
     android:layout_marginLeft="10dp" />  
 </RelativeLayout>  

nav_drawer.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   tools:showIn="navigation_view">  
   <group android:checkableBehavior="single">  
     <item  
       android:id="@+id/home"  
       android:icon="@drawable/ic_home"  
       android:title="Home" />  
     <item  
       android:id="@+id/message"  
       android:icon="@drawable/ic_home2"  
       android:title="Message" />  
     <item  
       android:id="@+id/help"  
       android:icon="@drawable/ic_help"  
       android:title="how_to_use" />  
   </group>  
   <group android:checkableBehavior="single">  
     <item android:title="Communication">  
       <menu>  
         <item  
           android:id="@+id/rate"  
           android:icon="@drawable/ic_rate"  
           android:title="Rate" />  
         <item  
           android:id="@+id/share"  
           android:icon="@drawable/ic_share"  
           android:title="Share" />  
         <item  
           android:id="@+id/privacy"  
           android:icon="@drawable/ic_privacy"  
           android:title="Privacy" />  
       </menu>  
     </item>  
   </group>  
 </menu>  
If you get the error of src ie picture then you can right click on res or drawable folder and click on vector asset and create a picture like this image.
Now we have to coding in Mainactivity .java, you paste the code below into manactivity.java.
MainActivity.java
 import android.os.Bundle;  
 import android.view.MenuItem;  
 import android.widget.Toast;  
 import androidx.annotation.NonNull;  
 import androidx.appcompat.app.ActionBarDrawerToggle;  
 import androidx.appcompat.app.AppCompatActivity;  
 import androidx.appcompat.widget.Toolbar;  
 import androidx.core.view.GravityCompat;  
 import androidx.drawerlayout.widget.DrawerLayout;  
 import androidx.fragment.app.Fragment;  
 import androidx.fragment.app.FragmentManager;  
 import com.google.android.material.navigation.NavigationView;  
 public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {  
   Toolbar toolbar;  
   DrawerLayout drawerLayout;  
   NavigationView navigationView;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     toolbar = findViewById(R.id.toolbarmain);  
     navigationView = findViewById(R.id.navi);  
     navigationView = findViewById(R.id.navi);  
     setSupportActionBar(toolbar);  
     navigationView.setNavigationItemSelectedListener(this);  
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);  
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(  
         this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);  
     drawer.addDrawerListener(toggle);  
     drawer.setScrimColor(000);  
     toggle.syncState();  
     if(savedInstanceState == null) {  
       navigationView.getMenu().getItem(0).setChecked(true);  
       Fragment fragment = new HomeFragment();  
       FragmentManager fm = getSupportFragmentManager();  
       fm.beginTransaction().replace(R.id.framelayout, fragment).commit();  
     }  
   }  
   @Override  
   public void onBackPressed() {  
     DrawerLayout drawer = findViewById(R.id.drawer);  
     if (drawer.isDrawerOpen(GravityCompat.START)) {  
       drawer.closeDrawer(GravityCompat.START);  
     }  
     else {  
       super.onBackPressed();  
     }  
   }  
   @Override  
   public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {  
     int v = menuItem.getItemId();  
     if (v == R.id.home) {  
       Fragment fragment = new HomeFragment();  
       FragmentManager fm = getSupportFragmentManager();  
       fm.beginTransaction().replace(R.id.framelayout, fragment).commit();  
     } else if (v == R.id.message) {  
         Fragment fragment = new MessageFragment();  
         FragmentManager fm = getSupportFragmentManager();  
         fm.beginTransaction().replace(R.id.framelayout, fragment).commit();}  
     else if (v == R.id.help) {  
       Toast.makeText(this, "Click on Help ", Toast.LENGTH_SHORT).show();  
     } else if (v == R.id.rate) {  
       Toast.makeText(this, "Click on rate us ", Toast.LENGTH_SHORT).show();  
     } else if (v == R.id.share) {  
       Toast.makeText(this, "Click on share ", Toast.LENGTH_SHORT).show();  
     }  
     else if (v==R.id.privacy)  
     {  
       Toast.makeText(this, "Click on privacy ", Toast.LENGTH_SHORT).show();  
     }  
     drawerLayout = findViewById(R.id.drawer);  
     drawerLayout.closeDrawer(GravityCompat.START);  
     return true;  
   }  
 }  
After pasting this code you will see some error. First to fix this of the string in ActionDrawerToggle, after opening the value >> string, you have to paste this code in string.xml
  <string name="navigation_drawer_open">Open navigation drawer</string>  
   <string name="navigation_drawer_close">Close navigation drawer</string>  
Then you will see the theme below the string, just you have to do NoActionBar in it instead of DarkActionBar because we are using the new toolbar.
theme.xml
 <resources xmlns:tools="http://schemas.android.com/tools">  
   <!-- Base application theme. -->  
   <style name="Theme.TabLayoutProject" parent="Theme.MaterialComponents.DayNight.NoActionBar">  
     <!-- Primary brand color. -->  
     <item name="colorPrimary">@color/purple_500</item>  
     <item name="colorPrimaryVariant">@color/purple_700</item>  
     <item name="colorOnPrimary">@color/white</item>  
     <!-- Secondary brand color. -->  
     <item name="colorSecondary">@color/teal_200</item>  
     <item name="colorSecondaryVariant">@color/teal_700</item>  
     <item name="colorOnSecondary">@color/black</item>  
     <!-- Status bar color. -->  
     <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>  
     <!-- Customize your theme here. -->  
   </style>  
 </resources>  
Then we will get a fragment error to fix it right click on java package, select new -> fragment -> select Fragment(Blank) and paste java and xml code
HomeFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.fragment.app.Fragment;  
 import androidx.viewpager.widget.ViewPager;  
 import com.google.android.material.tabs.TabLayout;  
 public class HomeFragment extends Fragment {  
   ViewPager viewPager;  
   TabLayout tabLayout;  
   public HomeFragment() {  
     // Required empty public constructor  
   }  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container,  
                Bundle savedInstanceState) {  
     View v=inflater.inflate(R.layout.home_fragment, container, false);  
     viewPager = (ViewPager) v.findViewById(R.id.home_viewPager);  
     tabLayout = (TabLayout) v.findViewById(R.id.home_tabLayout);  
     viewPager.setOffscreenPageLimit(3);  
     HomeViewPagerAdapter adapter = new HomeViewPagerAdapter(getChildFragmentManager());  
     adapter.addTabs("Chat",new CallFragment());  
     adapter.addTabs("Status",new StatusFragment());  
     adapter.addTabs("Call",new ChatFragment());  
     viewPager.setAdapter(adapter);  
     tabLayout.setupWithViewPager(viewPager);  
     return v;  
   }  
 }  
home_fragment.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <com.google.android.material.appbar.AppBarLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content">  
     <com.google.android.material.tabs.TabLayout  
       android:id="@+id/home_tabLayout"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:background="@color/purple_500"  
       app:tabIndicatorColor="@android:color/white"  
       app:tabIndicatorHeight="3dp"  
       app:tabSelectedTextColor="@android:color/white"  
       app:tabTextColor="@android:color/white">  
     </com.google.android.material.tabs.TabLayout>  
   </com.google.android.material.appbar.AppBarLayout>  
   <androidx.viewpager.widget.ViewPager  
     android:id="@+id/home_viewPager"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     app:layout_behavior="@string/appbar_scrolling_view_behavior" />  
 </androidx.coordinatorlayout.widget.CoordinatorLayout>  
MessageFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.fragment.app.Fragment;  
 import androidx.viewpager.widget.ViewPager;  
 import com.google.android.material.tabs.TabLayout;  
 public class MessageFragment extends Fragment {  
   ViewPager viewPager;  
   TabLayout tabLayout;  
   public MessageFragment() {  
     // Required empty public constructor  
   }  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container,  
                Bundle savedInstanceState) {  
     View v=inflater.inflate(R.layout.home_fragment, container, false);  
     viewPager = (ViewPager) v.findViewById(R.id.home_viewPager);  
     tabLayout = (TabLayout) v.findViewById(R.id.home_tabLayout);  
     viewPager.setOffscreenPageLimit(3);  
     HomeViewPagerAdapter adapter = new HomeViewPagerAdapter(getChildFragmentManager());  
     adapter.addTabs("Image",new ImageFragment());  
     adapter.addTabs("Video",new VideoFragment());  
     adapter.addTabs("Download",new DownloadFragment());  
     viewPager.setAdapter(adapter);  
     tabLayout.setupWithViewPager(viewPager);  
     return v;  
   }  
 }  
HomeViewPagerAdapter.java
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.fragment.app.Fragment;  
 import androidx.fragment.app.FragmentManager;  
 import androidx.fragment.app.FragmentPagerAdapter;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.Map;  
 public class HomeViewPagerAdapter extends FragmentPagerAdapter {  
   ArrayList<String> arrayListText = new ArrayList<>();  
   ArrayList<Fragment> fragmentArrayList = new ArrayList<>();  
   private Map<Integer, String> mFragmentTags;  
   private FragmentManager mFragmentManager;  
   public HomeViewPagerAdapter(FragmentManager fm) {  
     super(fm);  
     mFragmentManager = fm;  
     mFragmentTags = new HashMap<>();  
   }  
   @NonNull  
   @Override  
   public Fragment getItem(int position) {  
     return fragmentArrayList.get(position);  
   }  
   @Override  
   public CharSequence getPageTitle(int position) {  
     return arrayListText.get(position);  
   }  
   @Override  
   public int getCount() {  
     return arrayListText.size();  
   }  
   public void addTabs(String text, Fragment fragment) {  
     arrayListText.add(text);  
     fragmentArrayList.add(fragment);  
   }  
   @NonNull  
   @Override  
   public Object instantiateItem(@NonNull ViewGroup container, int position) {  
     Object obj = super.instantiateItem(container, position);  
     if (obj instanceof Fragment) {  
       // record the fragment tag here.  
       Fragment f = (Fragment) obj;  
       String tag = f.getTag();  
       mFragmentTags.put(position, tag);  
     }  
     return obj;  
   }  
   @Override  
   public int getItemPosition(@NonNull Object object) {  
     return POSITION_NONE;  
   }  
   public Fragment getFragment(int position) {  
     String tag = mFragmentTags.get(position);  
     if (tag == null)  
       return null;  
     return mFragmentManager.findFragmentByTag(tag);  
   }  
 }  
ChatFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class ChatFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.chat_fragment,container,false);  
   }  
 }  
chat_fragment
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Chat Fragment"  
     android:textSize="29sp"  
     android:textColor="@color/purple_500"  
     android:layout_centerInParent="true"/>  
 </RelativeLayout>  
StatusFragment.java
import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class StatusFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.status_fragment,container,false);  
   }  
 }  
status_fragment.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Status Fragment"  
     android:textSize="29sp"  
     android:textColor="@color/purple_500"  
     android:layout_centerInParent="true"/>  
 </RelativeLayout>  
CallFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class CallFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.call_fragment,container,false);  
   }  
 }  
ImageFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class ImageFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.image_fragment,container,false);  
   }  
 }  
image_fragment.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Image Fragment"  
     android:textSize="29sp"  
     android:textColor="@color/purple_500"  
     android:layout_centerInParent="true"/>  
 </RelativeLayout>  
VideoFragment.java
import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class VideoFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.video_fragment,container,false);  
   }  
 }  
video_fragment.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Video Fragment"  
     android:textSize="29sp"  
     android:textColor="@color/purple_500"  
     android:layout_centerInParent="true"/>  
 </RelativeLayout>  
DownloadFragment.java
 import android.os.Bundle;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.fragment.app.Fragment;  
 public class DownloadFragment extends Fragment {  
   @Nullable  
   @Override  
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.download_fragment,container,false);  
   }  
 }  
download_fragment.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Download Fragment"  
     android:textSize="29sp"  
     android:textColor="@color/purple_500"  
     android:layout_centerInParent="true"/>  
 </RelativeLayout>  
hope that this article will be very useful for you.
Thank You ...

Post a Comment

0 Comments