Main navigation

Android Viewpager Example : Working with Tablayout in Android

adsense

Demo Video for Android Viewpager Example

Android Viewpager Example

Let’s start coding our Android Viewpager Example.

Android Viewpager Example

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name (We have named as Android Viewpager Example).
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps. Make sure build.grade has following code specially com.android.support:design:23.1.1:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

Create Fragments

First of all, we will create a blank fragment named Tablayout_in_Android. It should be created as shown in following image:

Android Viewpager Example

Following screen will appear after selection

Android Viewpager Example

Click Finish. So finally our fragment is created, corresponding to which an XML file is also generated in layout tab namely fragment_tablayout_in__android.xml . Following is how directory structure will look like:

Android Viewpager Example

Add following code in Tablayout_in_Android.java:

Tablayout_in_Android.java

package com.androidtutorialpoint.androidviewpagerexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tablayout_in_Android extends Fragment {

        public Tablayout_in_Android() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_tablayout_in__android, container, false);
        }





}

In the above fragment code, fragment_tablayout_in__android is used as layout file which was created automatically during creation of Fragment.

Creating Tabs

This is the tab that will be finally shown to user. Whatever things we add in this tab will be displayed to user. For the time being, we are trying to make it as simple as possible so we are just displaying default text as “Hello blank fragment”. Open fragment_tablayout_in__android.xml and add following code:

fragment_tablayout_in__android.xml

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
             xmlns:tools="https://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.androidtutorialpoint.androidviewpagerexample.Tablayout_in_Android">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"
        android:text="@string/hello_blank_fragment"/>

</FrameLayout>

Note: We will make Tablayout in Android in minimum steps possible, So we won’t make much changes in XML files. Just some basic important changes are required.

Fixed tabs should be used when you have limited number of tabs. These tabs are fixed in position. In android design support library lot of new elements like CoordinatorLayout, AppBarLayout, TabLayout and lot more were introduced. In this android viewpager example, we will use fixed tab. Open activity_main.xml and add tabMode=”fixed”.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.androidtutorialpoint.androidviewpagerexample.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

</android.support.design.widget.CoordinatorLayout>

Implementing The PageAdapter

This can be implemented by using either FragmentPagerAdapter or FragmentStatePagerAdapter. FragmentStatePagerAdapter of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages. FragmentPagerAdapter is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. Here we will use FragmentPagerAdapter.

class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

Implementing the Activity

Following main points should be noted before adding code in MainActivity.java:

  1. Activity needs to initialize its own PageAdapter
  2. addTabs: Add required number of Tablayout in Android by setting appropriate fragment and tab name.
  3. ViewPagerAdapter: Adapter class that provides fragments required for the android view pager example which we described just above.

MainActivity.java

package com.androidtutorialpoint.androidviewpagerexample;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        addTabs(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

    }

    private void addTabs(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new Tablayout_in_Android(), "ONE");
        adapter.addFrag(new Tablayout_in_Android(), "TWO");
        adapter.addFrag(new Tablayout_in_Android(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

In the above code, we are adding tablayout in android using function addTabs(viewPager). Here we have added three tabs but you can add more by creating more instances of class Tablayout_in_Android. So finally run this App, It will look like as follows:

Android Viewpager Example
You can also see demo of this android viewpager example in the video given at the start of tutorial. Hope you like. Let us know your views about how you liked our tutorial of tablayout in android by commenting below. Feel free to comment for any doubt or suggestion.



What’s Next?

You can see our other tutorials on material design like Android ScrollView, Expandablelistview,Spinner and GridView Tutorials etc.
For more awesome tutorials stay tuned .. and Don’t forget to subscribe our blog for latest android tutorials.

Also do Like our Facebook Page or Add us on Twitter.

Click on Download Now button to download the full code.

Android Viewpager Example


Reader Interactions

Comments

Leave a Reply

Advertisment ad adsense adlogger