Learn Android with Java and Kotlin
 

Create Tabs using ViewPager , TabLayout and FragmentPagerAdapter in Android

  • 1. Create a new android project
  • 2. Add ViewPager and TabLayout widget to the layout of the activity i.e main_activity.xml
    				<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    				    xmlns:tools="http://schemas.android.com/tools"
    				    android:layout_width="match_parent"
    				    android:layout_height="match_parent"
    				    android:orientation="vertical">
    
    				    <android.support.design.widget.TabLayout
    				        android:layout_width="match_parent"
    				        android:layout_height="wrap_content"
    				        android:id="@+id/tabs"
    				        />
    
    				    <android.support.v4.view.ViewPager
    				        android:layout_width="match_parent"
    				        android:layout_height="wrap_content"
    				        android:id="@+id/view_pager"
    				        />
    				</LinearLayout>
    
  • 3. Initialize the UI components in MainActivity.java
    package com.droidmonk.viewpagerdemo;
    
    import android.support.design.widget.TabLayout;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity {
    
        private ViewPager mViewPager;
        private TabLayout mTabs;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mViewPager= (ViewPager) findViewById(R.id.view_pager);
            mTabs= (TabLayout) findViewById(R.id.tabs);
    
        }
    }
    
  • 4. Lets create the fragments to be used as pages for the viewpager.

    We have created three fragments with different background colors.

  • 5. Create an adapter for the viewpager.
    1. Create a class ViewPagerAdapter and extend FragmentPagerAdapter
    Now lets add the methods to implement and the default constructor , and ViewPagerAdapter look like —

    				public class ViewPagerAdapter extends FragmentPagerAdapter {
    
    			    public ViewPagerAdapter(FragmentManager fm) {
    			        super(fm);
    			    }
    
    			    @Override
    			    public Fragment getItem(int position) {
    			        return null;
    			    }
    
    			    @Override
    			    public CharSequence getPageTitle(int position) {
    			        return super.getPageTitle(position);
    			    }
    
    			    @Override
    			    public int getCount() {
    			        return 0;
    			    }
    			}
    

    2. Create two List variables to hold the fragments and the page titles(TO be displayed on the tabs)
    Initialize them in the constructor.
    Create a method add Fragments and titles to the list variable.

    	
    
    			    private List mPages;
    			    private List mTitles;
    
    		        ViewPagerAdapter(FragmentManager fm) {
    			        super(fm);
    
    			        mPages=new ArrayList<>();
    			        mTitles=new ArrayList<>();
    
    			    }
    
    			    void addFragment(Fragment page, String title)
    			    {
    			        mPages.add(page);
    			        mTitles.add(title);
    			    }
    
    

    3. Override the implemented methods .
    a. getCount() should return the total number of pages to be diplayed i.e. mPages.size() in our case
    b. getItem(int position) returns the fragment to be diplayed at the specified position.
    c. getPageTitle(int position) is used to provide the title of the page at the specified position, we shall use this to name the tabs.

    	
    
    	class ViewPagerAdapter extends FragmentPagerAdapter {
    
    	    private List mPages;
    	    private List mTitles;
    
    	    ViewPagerAdapter(FragmentManager fm) {
    	        super(fm);
    
    	        mPages=new ArrayList<>();
    	        mTitles=new ArrayList<>();
    
    	    }
    
    	    void addFragment(Fragment page, String title)
    	    {
    	        mPages.add(page);
    	        mTitles.add(title);
    	    }
    
    	    @Override
    	    public Fragment getItem(int position) {
    	        return mPages.get(position);
    	    }
    
    	    @Override
    	    public CharSequence getPageTitle(int position) {
    	        return mTitles.get(position);
    	    }
    
    	    @Override
    	    public int getCount() {
    	        return mPages.size();
    	    }
    	}
    
    
    
  • 6. Set the adapter to the viewpager

    mViewPager.setAdapter(mAdapter);

  • 7. Link the tablayout to the viewpager

    mTabs.setupWithViewPager(mViewPager);

package com.droidmonk.viewpagerdemo;

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private TabLayout mTabs;
    private ViewPagerAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*Initialize UI*/
        mViewPager= (ViewPager) findViewById(R.id.view_pager);
        mTabs= (TabLayout) findViewById(R.id.tabs);

        /*Create the adapter*/
        mAdapter=new ViewPagerAdapter(getSupportFragmentManager());
        mAdapter.addFragment(FrPageOne.newInstance(),getResources().getString(R.string.fr_1));
        mAdapter.addFragment(FrPageTwo.newInstance(),getResources().getString(R.string.fr_2));
        mAdapter.addFragment(FrPageThree.newInstance(),getResources().getString(R.string.fr_3));

        /*Add the adapter to the viewpager*/
        mViewPager.setAdapter(mAdapter);

        /*Link the tab to the viewpager*/
        mTabs.setupWithViewPager(mViewPager);

    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view_pager"
        />
</LinearLayout>
package com.droidmonk.viewpagerdemo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;

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

/**
 * Created by DroidMonk on 14-08-2017.
 */

class ViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mPages;
    private List<String> mTitles;

    ViewPagerAdapter(FragmentManager fm) {
        super(fm);

        mPages=new ArrayList<>();
        mTitles=new ArrayList<>();

    }

    void addFragment(Fragment page, String title)
    {
        mPages.add(page);
        mTitles.add(title);
    }

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

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

    @Override
    public int getCount() {
        return mPages.size();
    }
}
package com.droidmonk.viewpagerdemo;


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

public class FrPageOne extends Fragment {


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

    public static FrPageOne newInstance() {
        
        Bundle args = new Bundle();
        
        FrPageOne fragment = new FrPageOne();
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_page_one, container, false);
    }

}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    tools:context="com.droidmonk.viewpagerdemo.FrPageOne">

    <TextView
        android:layout_gravity="center"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/fr_1" />

</FrameLayout>

Leave a Reply

Your email address will not be published.