home top ad

How to implement TabLayout in Android using ViewPager and Fragments

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 TabLayout 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. Whenever the user clicks on the tab it will lead to the transaction of one Fragment to another. ViewPager is used to swipe between the tabs. WhatsApp, Facebook, etc are a very good example of TabLayout with ViewPager. This is how a TabLayout looks like.
Similarly, if you also want to show tablayout in your application, then follow this code.

We will use two steps to implements tab layout

TabLayout in Android using ViewPager and Fragments
[ Method 1 ]
Step 1. 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
 import androidx.appcompat.app.AppCompatActivity;  
 import androidx.appcompat.widget.Toolbar;  
 import androidx.viewpager.widget.ViewPager;  
 import android.os.Bundle;  
 import com.google.android.material.tabs.TabLayout;  
 public class MainActivity extends AppCompatActivity {  
   private Toolbar toolbar;  
   private TabLayout tabLayout;  
   private ViewPager viewPager;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     toolbar = (Toolbar) findViewById(R.id.toolbar);  
     setSupportActionBar(toolbar);  
     viewPager = (ViewPager) findViewById(R.id.viewpager);  
     setupViewPager(viewPager);  
     tabLayout = (TabLayout) findViewById(R.id.tabs);  
     tabLayout.setupWithViewPager(viewPager);  
   }  
   private void setupViewPager(ViewPager viewPager) {  
     ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());  
     adapter.addFragment(new ChatFragment(), "Chat");  
     adapter.addFragment(new StatusFragment(), "Status");  
     adapter.addFragment(new CallFragment(), "Call");  
     viewPager.setAdapter(adapter);  
   }  
 }  
This is also useful for you

  • How to Create Image Slider using ViewPager in android studio
  • How to create Swipeable Videos Like TikTok Using ViewPager2 in andriod studio
  • how to get all audio files in android programmatically
  • How to use SearchView in andriod studio
  • How to check internet Connection in androd studio
  • How to Create Bottom Sheet in android studio
  • How to Refresh a list Using RecyclerView in Android Studio
  • How to create Welcome Splash Screen with animation in android studio
  • How to create menu and sub menu in android studio
  • How to create a list item with RecyclerView in Android Studio
  • BottomNavigationView android example
  • How to create Text to Speech app in android studio
  • After pasting this code, you will see some error, follow the rule given below to fix that error.

    Rule:
    Create a ChatFragment by right click on java package, select new -> fragment -> select Fragment(Blank). Follow above step for StatusFragment and CallFragment. Now add the following code in chatfragment.xml file. Here a TextView is added in the layout. Now add the following code in statusfragment.xml file. Here a textView is added in the layout. Now add the following code in callfragment.xml file. Here a textView is added in the layout. Now Create a ViewPagerAdapter for our ViewPager by extending FragmentPagerAdapter class. In this class we will overide three methods getItem(), getCount() and getPageTitle(). getItem method gives the fragment with respect to the position, getCount method gives total number of fragments present and getPageTitle method gives the title of the fragment. Add the following code in MainActivity.java file. In this file we setup our adapter and attach our TabLayout with ViewPager.

    ViewPagerAdapter.java
     import androidx.fragment.app.Fragment;  
     import androidx.fragment.app.FragmentManager;  
     import androidx.fragment.app.FragmentPagerAdapter;  
     import java.util.ArrayList;  
     import java.util.List;  
     public class ViewPagerAdapter extends FragmentPagerAdapter {  
       private final List<Fragment> mFragmentList = new ArrayList<>();  
       private final List<String> mFragmentTitleList = new ArrayList<>();  
       public ViewPagerAdapter(FragmentManager manager) {  
         super(manager);  
       }  
       @Override  
       public Fragment getItem(int position) {  
         return mFragmentList.get(position);  
       }  
       @Override  
       public int getCount() {  
         return mFragmentList.size();  
       }  
       public void addFragment(Fragment fragment, String title) {  
         mFragmentList.add(fragment);  
         mFragmentTitleList.add(title);  
       }  
       @Override  
       public CharSequence getPageTitle(int position) {  
         return mFragmentTitleList.get(position);  
       }  
     }  
    
    Now below all Fragment Class and xml code:
    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.fragment_chat,container,false);  
       }  
     }  
    
    fragment_chat.xml
     <?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"  
       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="20sp"  
         android:textColor="@color/purple_700"  
         android:textStyle="bold"  
         app:layout_constraintBottom_toBottomOf="parent"  
         app:layout_constraintEnd_toEndOf="parent"  
         app:layout_constraintStart_toStartOf="parent"  
         app:layout_constraintTop_toTopOf="parent" />  
     </androidx.constraintlayout.widget.ConstraintLayout>  
    
    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.fragment_status,container,false);  
       }  
     }  
    
    fragment_status.xml
     <?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"  
       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="20sp"  
         android:textColor="@color/purple_700"  
         android:textStyle="bold"  
         app:layout_constraintBottom_toBottomOf="parent"  
         app:layout_constraintEnd_toEndOf="parent"  
         app:layout_constraintStart_toStartOf="parent"  
         app:layout_constraintTop_toTopOf="parent" />  
     </androidx.constraintlayout.widget.ConstraintLayout>  
    
    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 StatusFragment extends Fragment {  
       @Nullable  
       @Override  
       public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {  
         return inflater.inflate(R.layout.fragment_call,container,false);  
       }  
     }  
    
    fragment_call.xml
     <?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"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent">  
       <TextView  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:text="Call Fragment"  
         android:textSize="20sp"  
         android:textColor="@color/purple_700"  
         android:textStyle="bold"  
         app:layout_constraintBottom_toBottomOf="parent"  
         app:layout_constraintEnd_toEndOf="parent"  
         app:layout_constraintStart_toStartOf="parent"  
         app:layout_constraintTop_toTopOf="parent" />  
     </androidx.constraintlayout.widget.ConstraintLayout>  
    
    Here you are given a screenshot of the app
    TabLayout in Android using ViewPager and Fragments
    TabLayout in Android using ViewPager and Fragments
    TabLayout in Android using ViewPager and Fragments

Post a Comment

0 Comments