Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Implement Dynamic TabLayout in Android?

How to Implement Dynamic TabLayout in Android?

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:

RELATED ARTICLES

Most Popular

Recent Comments