Skip to main content

android - How to use TabLayout


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


import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private ActionBar mActionBar;

    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar


        // Get the application context
        mContext = getApplicationContext();

        // Get the application resources
        mResources = getResources();

        // Get the action bar instance
        mActionBar = getSupportActionBar();

        // Set a color for action bar
        mActionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));

        // Get the widgets reference from XML layout
        ViewPager pager = (ViewPager) findViewById(;
        // TabLayout provides a horizontal layout to display tabs.
        TabLayout tabLayout = (TabLayout) findViewById(;

        // Initialize a new PagerAdapter instance
        PagerAdapter adapter = new ColorsPagerAdapter(mContext);

        // Bind the PagerAdapter with ViewPager

            public void setupWithViewPager (ViewPager viewPager)
                The one-stop shop for setting up this TabLayout with a ViewPager.

                This method will:
                    Add a ViewPager.OnPageChangeListener that will forward events to this TabLayout.
                    Populate the TabLayout's tabs from the ViewPager's PagerAdapter.
                    Set our TabLayout.OnTabSelectedListener which will forward selected events
                    to the ViewPager
        // Attach the TabLayout with ViewPager object

        // Define some properties to TabLayout
            setSelectedTabIndicatorColor(int color)
                Sets the tab indicator's color for the currently selected tab.

            setBackground(Drawable background)
                Set the background to a given Drawable, or remove the background.
        // Set the tab background
        tabLayout.setBackground(new ColorDrawable(Color.RED));

            public void setTabMode (int mode)
                Set the behavior mode for the Tabs in this layout. The valid input options are:

                MODE_FIXED: Fixed tabs display all tabs concurrently and are best used with content
                    that benefits from quick pivots between tabs.
                MODE_SCROLLABLE: Scrollable tabs display a subset of tabs at any given moment, and
                    can contain longer tab labels and a larger number of tabs. They are best used
                    for browsing contexts in touch interfaces when users don’t need to directly
                    compare the tab labels. This mode is commonly used with a ViewPager.
                    mode : one of MODE_FIXED or MODE_SCROLLABLE.


            public void setTabsFromPagerAdapter (PagerAdapter adapter)
                Populate our tab content from the given PagerAdapter.

                Any existing tabs will be removed first. Each tab will have it's text set to the
                value returned from getPageTitle(int)

                adapter : the adapter to populate from

            public void setTabTextColors (int normalColor, int selectedColor)
                Sets the text colors for the different states (normal, selected) used for the tabs.
        // Set the tab text colors


import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.AbsListView.LayoutParams;
import android.widget.TextView;

public class ColorsPagerAdapter extends PagerAdapter {
    private Context mContext;
        When you implement a PagerAdapter, you must override the following methods at minimum:
            instantiateItem(ViewGroup, int)
            destroyItem(ViewGroup, int, Object)
            isViewFromObject(View, Object)

    ColorsPagerAdapter(Context context){
        this.mContext = context;

    // Get the colors
    private String[] getColors(){
        String[] colors = new String[]{
                public static int parseColor (String colorString)
                    This method only support the following color names
                "red", "Blue", "green", "black", "white",
                "gray", "cyan", "magenta", "yellow", "lightgray",
                "darkgray", /*"grey", "lightgrey", "darkgrey",*/ "aqua",
                "fuchsia", "lime", "maroon", "navy", "olive",
                "purple", "silver", "teal"
        return colors;

    // public abstract int getCount ()
    public int getCount(){
        return getColors().length;

    // public CharSequence getPageTitle (int position)
    public CharSequence getPageTitle(int position){
        return getColors()[position];

    // public Object instantiateItem (ViewGroup container, int position)
    public Object instantiateItem(ViewGroup container, int position){
        // Initialize a new RelativeLayout instance
        RelativeLayout rl = new RelativeLayout(mContext);
        // Initialize a new LayoutParams object for RelativeLayout
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        // Set the parameters for newly created RelativeLayout

        // Get the current color from colors array
        int color = Color.parseColor((String) getPageTitle(position));

        // Set a background for RelativeLayout

        // Initialize a new TextView widget
        TextView tv = new TextView(mContext);
        // Set the TextView layout parameters

        // Assign some properties to TextView widget
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 85);

        // Initialize a new Typeface instance
        Typeface typeface = Typeface.create(Typeface.SANS_SERIF,Typeface.BOLD);
        // Define the TextView font

        // Draw a shadow around the TextView text
                15, // radius
                0, // dx
                0, // dy

        // Put the TextView into RelativeLayout

        // Put the RelativeLayout to the container

        // Return the RelativeLayout
        return rl;

    // public void destroyItem (ViewGroup container, int position, Object object)
    public void destroyItem(ViewGroup container, int position, Object object){

    // public abstract boolean isViewFromObject (View view, Object object)
    public boolean isViewFromObject(View view, Object object){
        return view == object;


    // Custom method to create a GradientDrawable object
    protected GradientDrawable getGradientDrawable(int color){
        GradientDrawable gradient = new GradientDrawable();
        int darkerColor = getDarkerColor(color);
        int lighterColor = getLighterColor(color);
        gradient.setColors(new int[]{darkerColor,lighterColor});
        return gradient;

    // Custom method to get a darker color
    protected int getDarkerColor(int color){
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] = 0.8f *hsv[2];
        return Color.HSVToColor(hsv);

    // Custom method to get a lighter color
    protected int getLighterColor(int color){
        float[] hsv = new float[3];
        hsv[2] = 0.2f + 0.8f * hsv[2];
        return Color.HSVToColor(hsv);

    // Custom method to get reverse color
    protected int getReverseColor(int color){
        float[] hsv = new float[3];
      , // Red value
      , // Green value
      , // Blue value
        hsv[0] = (hsv[0] + 180) % 360;
        return Color.HSVToColor(hsv);
build.gradle dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="" xmlns:tools="" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…