ViewPager with TabLayout Android Studio

viewpager with custom tab

In this article we will learn how to create ViewPager with TabLayout Android Studio. We use ViewPager to create a view the works as Image Slider. In this tutorial I will use the ViewPager2 Class and accordingly I will use the RecyclerView Adapter Class. Lets create a new android studio project with Java language.

First, we need to add the required dependences as following in the Gradle file, in module Gradle file. Note, that I am using the Java version of 1.8 and ViewBinding.

plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.viewpagerwithcustomicons"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures {
        viewBinding true
        dataBinding true


    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.android.support:design:31.0.0'
    implementation 'com.github.bumptech.glide:glide:4.12.0'
}

Then, Open theme file in the res folder and set the app theme as NOACTIONBAR.

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.ViewPagerWithCustomIcons" 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>

After that, Select some file images files from your computer, name the with small caps, without number and without spaces and past them in the drawable folder.

Then, Open main_activity.xml file and replace the following code.

<?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"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="40dp"
        android:background="@android:color/transparent"
        android:minHeight="30dp"
        app:tabGravity="fill"
        app:tabMaxWidth="50dp"
        app:tabIndicatorColor="@color/white"
        android:layout_centerHorizontal="true"
        app:tabSelectedTextColor="@color/purple_700"
        app:tabTextColor="@color/purple_200" />

</RelativeLayout>

The above code represents the xml layout file of the main activity. It consists of Relative layout witn ViewPager2 and TabLayout.

ViewPager2 Adapter

The ViewPager2 is advanced type the ViewPager. Moreover it requires a Java Class the extends the RecyclerView Adapter Class. This class need to create a new resource layout file that represents the row layout of viewpager adapter. So, create a new resource layout file and name it “view_pager_row_layout” ,use the following code.

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        app:srcCompat="@mipmap/ic_launcher"
        tools:ignore="ContentDescription" />
</RelativeLayout>

Next, we need to create and Java class. I named it as ViewPagerAdapter class as the following code.

package com.example.viewpagerwithcustomicons;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.viewpagerwithcustomicons.databinding.ViewPagerRowLayoutBinding;

public class ViewPagerRecyclerAdapter extends RecyclerView.Adapter<ViewPagerRecyclerAdapter.MyViewHolder> {
    private final int[] imagesArray;
    private Context context;

    public ViewPagerRecyclerAdapter(int[] imagesArray, Context context) {
        this.imagesArray = imagesArray;
        this.context =context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewPagerRowLayoutBinding viewPagerRowLayoutBinding = ViewPagerRowLayoutBinding.inflate(
                LayoutInflater.from(parent.getContext()),parent,false
        );
        return new MyViewHolder(viewPagerRowLayoutBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Glide.with(context).load(imagesArray[position]).into(holder.viewPagerRowLayoutBinding.imageView);
    }

    @Override
    public int getItemCount() {
        return imagesArray.length;
    }


    static class MyViewHolder extends RecyclerView.ViewHolder{
        ViewPagerRowLayoutBinding viewPagerRowLayoutBinding;
        public MyViewHolder(  ViewPagerRowLayoutBinding viewPagerRowLayoutBinding) {
            super(viewPagerRowLayoutBinding.getRoot());
            this.viewPagerRowLayoutBinding = viewPagerRowLayoutBinding;
        }
    }
}

I am using the ViewBindig in this class if you are not familliar with viewbinding and databinding click here.

Next, we need to work with the main activity java class. first setup the viewbinding by creating a Field of MainActivityBinding. MainActivityBinding is automatically created by the android studio when enabled the viewbidnig in Gradle file. Further more any new resource layout file it’s binding file will be created.

The main acctivity jave file contains the following code.

First, create an Integer array of the drawable resource image’s names.

Then, Create a method that returns a CircleImageView which represent the Custom Icon of the tab layout. After creating a new Instance of previously created viewpager adapter class. The TabLayout Mediator method which binds the tab layout with the viewpager2.

package com.example.viewpagerwithcustomicons;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.viewpagerwithcustomicons.databinding.ActivityMainBinding;
import com.google.android.material.tabs.TabLayoutMediator;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {

    private final int[] imagesArray = {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        com.example.viewpagerwithcustomicons.databinding.ActivityMainBinding activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        ViewPagerRecyclerAdapter viewPagerRecyclerAdapter = new ViewPagerRecyclerAdapter(imagesArray,this);
        activityMainBinding.viewPager.setAdapter(viewPagerRecyclerAdapter);
        new TabLayoutMediator(activityMainBinding.tablayout, activityMainBinding.viewPager, (tab, position) ->
                tab.setCustomView(createTabItemView(imagesArray[position]))).attach();
    }

    private CircleImageView createTabItemView(int resourceId){
        CircleImageView imageView = new CircleImageView(this);
        imageView.setBorderColor(getResources().getColor(R.color.white));
        imageView.setBorderWidth(5);


        Glide.with(getApplicationContext()).load(resourceId).into(imageView);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        imageView.setLayoutParams(params);
        return imageView;
    }
}

Finally, run the app and comment us the result or errors if found. Best Regards

viewpager with custom icon

Read More About ViewPager2 from here

Related posts

Leave a Comment