STEP 1 MAIN.XML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">




    <com.google.android.material.tabs.TabLayout

        style="@style/AppTheme"

        android:id="@+id/tabLayout"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:background="#FFF">

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager

        android:id="@+id/viewPager"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/tabLayout"

        android:layout_centerInParent="true"

        android:layout_marginTop="0dp"

        tools:layout_editor_absoluteX="8dp" />


</RelativeLayout>


STEP  2 MAIN.JAVA

package in.learncodewithrk.tablayout;


import androidx.appcompat.app.AppCompatActivity;

import androidx.viewpager.widget.ViewPager;


import android.os.Bundle;


import com.google.android.material.tabs.TabLayout;


public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;

    ViewPager viewPager;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);




        tabLayout = findViewById(R.id.tabLayout);

        viewPager = findViewById(R.id.viewPager);

        tabLayout.addTab(tabLayout.newTab().setText("Home"));

        tabLayout.addTab(tabLayout.newTab().setText("Course"));

        tabLayout.addTab(tabLayout.newTab().setText("Service"));

        tabLayout.addTab(tabLayout.newTab().setText("Contact US"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),

                tabLayout.getTabCount());

        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override

            public void onTabSelected(TabLayout.Tab tab) {

                viewPager.setCurrentItem(tab.getPosition());

            }

            @Override

            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override

            public void onTabReselected(TabLayout.Tab tab) {

            }

        });

    }

}

READ MORE >>

GITHUB : https://github.com/LearncodeWithRk/Androidx-TabLayout