The Wayback Machine - https://web.archive.org/web/20240914210343/https://www.geeksforgeeks.org/how-to-implement-dynamic-tablayout-in-android/
Open In App

How to Implement Dynamic TabLayout in Android?

Last Updated : 15 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn about how to add Dynamic TabLayout with ViewPager in an app. TabLayout provides a horizontal layout to display tabs. Here we will be just specifying the number of tabs we want to have. WhatsApp, Facebook, etc are a very good example of TabLayout with ViewPager. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Implement Dynamic TabLayout in Android

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.   

implementation ‘com.android.support:design:26.1.0’

In this project we are Creating these files: 

  •  One Java file with the name DynamicFragmentAdapter
  •  One Fragment with the name DynamicFragment
  •  One Activity of name DynamicActivity

Step 3: Working with the DynamicFragmentAdapter.java file

Go to the DynamicFragmentAdapter.java file and refer to the following code.

// returnthe mNumOfTabs
@Override
public int getCount() {
    return mNumOfTabs;
}

 Below is the code for the DynamicFragmentAdapter.java file.

Java




import android.os.Bundle;
  
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
  
public class DynamicFragmentAdapter extends FragmentStatePagerAdapter {
    private int mNumOfTabs;
  
    DynamicFragmentAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }
  
    // get the current item with position number
    @Override
    public Fragment getItem(int position) {
        Bundle b = new Bundle();
        b.putInt("position", position);
        Fragment frag = DynamicFragment.newInstance();
        frag.setArguments(b);
        return frag;
    }
  
    // get total number of tabs
    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}


Step 4: Working with the fragment_dynamic.xml file

Go to the fragment_dynamic.xml  and refer to the following code. Below is the code for the fragment_dynamic.xml file 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">
  
    <TextView
        android:id="@+id/commonTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="zxjhcvzxvchjzxbhj"
        android:textColor="@color/purple_500"
        android:textStyle="bold" />
  
</RelativeLayout>


Step 5: Working with the DynamicFragment.java file

Go to the DynamicFragment.java file and refer to the following code. 

// initialise the categories
private void initViews(View view) {
   TextView textView=view.findViewById(R.id.commonTextView);
   textView.setText(String.valueOf("Category :  "+getArguments().getInt("position")));
}

Below is the code for the DynamicFragment.java file. 

Java




import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
  
public class DynamicFragment extends Fragment {
      
    public static DynamicFragment newInstance() {
        return new DynamicFragment();
    }
  
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
  
    // adding the layout with inflater
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        initViews(view);
        return view;
    }
  
    // initialise the categories
    private void initViews(View view) {
        TextView textView = view.findViewById(R.id.commonTextView);
        textView.setText(String.valueOf("Category :  " + getArguments().getInt("position")));
    }
  
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
  
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
  
    // pause function call
    @Override
    public void onPause() {
        super.onPause();
    }
  
    // resume function call
    @Override
    public void onResume() {
        super.onResume();
    }
  
    // stop when we close
    @Override
    public void onStop() {
        super.onStop();
    }
  
    // destroy the view
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
  
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}


Step 6: Working with the activity_dynamic.xml file

Go to the activity_dynamic.xml file and refer to the following code. Below is the code for the activity_dynamic.xml file 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
  
        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="4dp"
            app:tabMode="scrollable"
            app:tabTextColor="@android:color/white" />
  
    </com.google.android.material.appbar.AppBarLayout>
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
  
        <androidx.viewpager.widget.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
  
    </RelativeLayout>
      
</androidx.coordinatorlayout.widget.CoordinatorLayout>


Step 7: Working with the DynamicActivity.java file

Go to the DynamicActivity.java file and refer to the following code. 

// show all the tab using DynamicFragmnetAdapter
private void setDynamicFragmentToTabLayout() {
  for (int i = 0; i < 10; i++) {
         mTabLayout.addTab(mTabLayout.newTab().setText("Page: " + i));
    }
DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
viewPager.setAdapter(mDynamicFragmentAdapter);
viewPager.setCurrentItem(0);
}

Below is the code for the DynamicActivity.java file 

Java




import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
import com.google.android.material.tabs.TabLayout;
  
public class DynamicActivity extends AppCompatActivity {
  
    private ViewPager viewPager;
    private TabLayout mTabLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic);
        initViews();
    }
  
    private void initViews() {
          
        // initialise the layout
        viewPager = findViewById(R.id.viewpager);
        mTabLayout = findViewById(R.id.tabs);
          
        // setOffscreenPageLimit means number 
        // of tabs to be shown in one page
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // setCurrentItem as the tab position
                viewPager.setCurrentItem(tab.getPosition());
            }
  
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
  
            }
  
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
  
            }
        });
        setDynamicFragmentToTabLayout();
    }
      
    // show all the tab using DynamicFragmnetAdapter
    private void setDynamicFragmentToTabLayout() {
        // here we have given 10 as the tab number
        // you can give any number here
        for (int i = 0; i < 10; i++) {
            // set the tab name as "Page: " + i
            mTabLayout.addTab(mTabLayout.newTab().setText("Page: " + i));
        }
        DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
          
        // set the adapter
        viewPager.setAdapter(mDynamicFragmentAdapter);
          
        // set the current item as 0 (when app opens for first time)
        viewPager.setCurrentItem(0);
    }
}


Output:



Similar Reads

How to Implement TabLayout with Icon in Android?
TabLayout is used to implement horizontal tabs. TabLayout is introduced in the design support library to implement tabs. Tabs are created using the newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout usi
4 min read
How to implement a TabLayout in Android using ViewPager and Fragments
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 click
3 min read
Coordinator TabLayout in Android
Many applications use TabLayout in which we have to show an image above the TabLayout. This type of UI design is mainly seen in Restaurant apps and many more. In this article, we will take a look at implementing the same type of view using Coordinator TabLayout in our Android App using Android Studio. What we are going to build in this article? We
8 min read
How to implement our own Dynamic Array class in Java?
Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. ArrayList elements are placed in contiguous storage so that
4 min read
Dynamic Fragment in Android
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments are more responsive and flexible than Static Fragme
4 min read
Dynamic CheckBox in Android with Examples
Android offers a wide variety of widgets for user interactions and CheckBox is one among them. CheckBox is a special kind of button with two states that can be either checked or unchecked. They serve as a simple tool to gather information from the user without much hassle. They are generally used to mark things as completed by the user in task mana
3 min read
How to Create Dynamic WebView in Android with Firebase?
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading a website into your app which can be changed dyna
6 min read
How to Create Dynamic PDF Viewer in Android with Firebase?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Android. Inside this, we add the URL for PDF inside our
8 min read
How to Create a Dynamic Video Player in Android with Firebase Realtime Database?
Most of the apps use the video player to display so many videos inside their application. So for playing the video the app plays the video from its video URL. But what if we want to update that video on a real-time basis. So, in that case, we have to update our database and then later on we have to update our APK. So this is not an efficient way to
8 min read
How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.
7 min read
Dynamic Splash Screen in Android
A Dynamic Splash screen is a more personalized image or graphic that is displayed when an application is loaded or launched. Dynamic Splash Screen consists of animation or moving graphics. It appears for a fraction of a second. It creates a sense of anticipation or excitement for the user and helps organizations with branding and establishing ident
3 min read
How to Use Dagger in Dynamic Feature Module in Android?
In our previous article, we learned how to set up dagger in an Android project with a multi-module architecture. Click here to see how we can use Dagger in Multi-Module Architecture. We will be expanding on the project that we worked on in our previous project. But first, we must learn how to create and configure a dynamic-feature module. Click her
3 min read
Dynamic Spinner in Android
Many times in android applications we have to create any view dynamically without writing any XML code. For that, we can create our view using our Kotlin or Java file. In this article, we will take a look at How to Dynamically create a spinner in an android application. A sample video is given below to get an idea about what we are going to do in t
6 min read
Dynamic Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android. A sample video is given below to get an idea about
7 min read
Dynamic ImageSwitcher in Android
Android ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. In this article, we will take a look at How to Create a Dynamic Image Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article.
8 min read
Dynamic TextSwitcher in Android
Text Switcher is a widget in android that contains multiple text views and we can display one text at a time in it. In this article, we will take a look at How to implement a Dynamic Text Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-co
8 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading a website into your app which can be changed dynam
8 min read
How to Generate Dynamic Multiple Buttons in Android?
In Android Studio, buttons are graphical user interface (GUI) elements that users can click or tap to perform an action. Buttons are typically represented by a rectangular or rounded rectangular shape with a label or an icon. In this article, we will learn to make dynamic multiple buttons in android studio. By which we can make unlimited buttons in
3 min read
Android Jetpack Compose - Dynamic Progress Bar with Text
Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android bringing your apps to life with less code, powerful tools, and intuitive Kotlin APIs. It makes building Android UI faster and easier This toolkit offers a wide range of pre-built UI components, allowing developers to easily de
6 min read
How to Create Dynamic GridView in Android using Firebase Firestore?
GridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the
9 min read
How to Create Dynamic Auto Image Slider in Android with Firebase?
We have seen many apps that display images in the slider format as that of banners which slide automatically. This type of feature of the auto image slider is seen in many E-commerce sites. This feature is seen in many apps which are having images in them. In this article, we will take a look at How to Create a dynamic Auto Image Slider in Android.
9 min read
How to Create Dynamic Shortcuts of an Android Applications?
In Android Phones, when an Application is held for more than a second, certain app actions appear in a list. These app actions are nothing but shortcuts for performing and actions without opening the application. Shortcuts for an application are a list of features (quick services) that helps the users to easily and quickly jump to particular featur
5 min read
How to Display Dynamic AlertDialog in Android using Firebase Firestore?
Dynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interva
7 min read
How to Create Dynamic Bottom Sheet Dialog in Android using Firebase Firestore?
Bottom Sheet Dialog is one of the famous Material UI Component which is used to display data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android using Firebase Firestore.  What we are going to buil
7 min read
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?
HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is seen in many E-commerce apps to indicate categories in the app. And this RecyclerView is also dynamic so that the admin can add or remove any item from that RecyclerView at any time. So in this article,
10 min read
How to Create Dynamic ListView in Android using Firebase Firestore?
ListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the implementation of ListView using Firebase Firestor
9 min read
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Realtime Database?
HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is mostly seen in many E-commerce apps to indicate categories in the app. As we have already seen in Amazon Shopping App. So in this article, we will take a look at creating a Dynamic Horizontal Recycler V
7 min read
How to Create Dynamic Intro Slider in Android using Firebase Firestore?
We have seen creating a basic Intro Slider in Android which is used to inform our users regarding the features of our app and many more. In this article, we will take a look at the implementation of dynamic Intro Slider in our app with the help of Firebase. With the help of Firebase Firestore, we can change all the data dynamically from the Firebas
11 min read
How to Create a Dynamic Widget of an Android App?
Prerequisites: How to Create a Basic Widget of an Android App?Widgets are the UI elements provided by an application for accessing some of its features remotely either from Home Screens or Lock Screens. Widgets can be Static or Dynamic meaning that the display elements don't change (Static) or change (Dynamic) with time. Through this article, let's
3 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experie
4 min read
Article Tags :
Practice Tags :