Android Layout Using ViewPager and Fragments

Please Share On:

Here, I will show you how can you display more screens on a single screen using tabs. You can swipe your screen to move to the next tab. Below is a screenshot of the screen having two tabs.

Creating your Android TabLayout

Here are the steps you need to follow to create your TabLayout screen.

  1. Add Design Support Dependencies
  2. Create TabLayout Fragment: tab1.xml and tab2.xml
  3. Create Java class for tab1 and tab2
  4. Create a Tab Pager Adapter in Java class. For example: TabPagerAdapter.java
  5. Creating TabLayout and ViewPager
  6. Remove ActionBar
  7. Add some code in Main Activity
  8. Create main_toolbar.xml
  9. Create colors.xml

Now, Let’s proceed in detail from step 1 to step 7.

1) Add Design Support Dependencies:

You can add your Android design support dependencies into either way:

1.1) Add directly in your Project Module: build.gradle

Open App -> Gradle Scripts ->build.gradle(Module: Your_Project_Name.app)

build.gradle

Add the below code inside dependencies

dependencies
{
implementation 'com.google.android.material:material:1.4.0'
}

OR



2.1) Select File -> Project Structure

Project Structure

2.2) Select Dependencies and click “+” sign

Add Dependencies

Choose “Library Dependencies” and select your Design Support Dependencies and click OK.

Library Dependencies


2) Create TabLayout Fragment: tab1.xml and tab2.xml

Now, you have to create tab1.xml and tab2.xml files. In the above screenshot, You can see that I have used only two tabs. If you need more than two tabs, create tab3.xml, tab4.xml accordingly, or your own name XML file.

Here, you will design your XML file accordingly to what exactly you want to display on your page. For instance, I am just displaying a text in each tab you slide. Here, is a code:

Tab1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="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:background="@color/background">

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Design Your Tab1 Here"/>
   
</RelativeLayout>

Tab2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="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:background="@color/background">

<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Design Your Tab2 Here"/>
   
</RelativeLayout>

3) Create Java class for tab1 and tab2

For tab1.xml and tab2.xml layout resource files, you need to create two java classes that will contain these resources as fragments.

Tab Java Classes

Add some code in Tab1.java and Tab2.java classes

Tab1.java

package com.elsebazaar.tabLayout;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

public class Tab1 extends Fragment {

    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.tab1, container, false);
    }
}

Tab2.java

package com.elsebazaar.tabLayout;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

public class Tab2 extends Fragment {

    //Overriden method onCreateView
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        return inflater.inflate(R.layout.tab2, container, false);
    }
}



4) Create a Tab Pager Adapter in Java class

Now create a Tab Pager Adapter java class and name as TapPagerAdapter. Paste the below code inside it.

TabPagerAdapter.java

package com.elsebazaar.tabactivity;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;

public class TabPagerAdapter extends FragmentPagerAdapter {

    //integer to count number of tabs
    int tabCount;


    //Constructor to the class
    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
    }


    //Overriding method getItem
    @NonNull
    @Override
    public Fragment getItem(int position) {
        //Returning the current tabs
        switch (position) {
            case 0:
                return new Tab1();
            case 1:
                return new Tab2();
            default:
                return null;
        }
    }

    //Overriden method getCount to get the number of tabs
    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String title = null;
        if (position == 0)
        {
            title = "list";
        }
        else if (position == 1)
        {
            title = "Collect";
        }
        return title;
    }
}



5) Creating TabLayout and ViewPager

Now, you need to create your TabLayout and ViewPager Resource file. Paste the following code in your activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/blue"
            app:tabSelectedTextColor="@color/white"
            app:tabTextColor="@color/white"
            tools:ignore="SpeakableTextPresentCheck" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:ignore="SpeakableTextPresentCheck" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


6) Remove Actionbar

Here, you have to remove your Actionbar and use the toolbar instead. To do this add the below code to your styles.xml file located under the values folder.

<resources> 
<!-- changing it to no actionbar -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


</resources>

7) Main Activity

Now, you have to add some code in your main activity to function your tabLayout.

package com.elsebazaar.tabactivity;

import android.os.Bundle;

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

import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    //Declare your TabLayout and ViewPager
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       //Replace action bar into toolbar
        Toolbar mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar); // Setting replace toolbar as the ActionBar

        //Initializing the tabLayout and viewLayout
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);

        //Creating our pager adapter
        TabPagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager());

        //Adding adapter to pager
        viewPager.setAdapter(adapter);

        //setUpWithViewPager is used to join tabLayout and viewPager
        tabLayout.setupWithViewPager(viewPager);

        //Adding onTabSelectedListener to swipe views
        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) {

           }

        });
    }
}

8) Create main_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:title="Tab layout"
        app:navigationIcon="@drawable/ic_baseline_menu_24"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

9) Create colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
    <color name="background">#CED6E0</color>
    <color name="blue">#4B6584</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>

Now, run your application you will get exactly the same output as shown below screenshot:



You may interest on the following topics:

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright @2023. All Right Reserved.


Social media & sharing icons powered by UltimatelySocial