Friday, November 20, 2015

android - How to use TabLayout

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/sliding_tabs"
    />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.tablayoutexample;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.TabLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.support.v4.view.ViewPager;
import android.support.v4.view.PagerAdapter;


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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 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(R.id.pager);
        // TabLayout provides a horizontal layout to display tabs.
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);

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

        // Bind the PagerAdapter with ViewPager
        pager.setAdapter(adapter);

        /*
            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
        tabLayout.setupWithViewPager(pager);

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

        /*
            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.
                Parameters
                    mode : one of MODE_FIXED or MODE_SCROLLABLE.

        */
        tabLayout.setTabMode(TabLayout.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)

            Parameters
                adapter : the adapter to populate from
        */
        //tabLayout.setTabsFromPagerAdapter(adapter);

        /*
            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
        tabLayout.setTabTextColors(Color.BLACK,Color.WHITE);
    }
}
ColorsPagerAdapter.java

package com.cfsuman.me.tablayoutexample;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.support.v4.view.PagerAdapter;
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)
            getCount()
            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 ()
    @Override
    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)
    @Override
    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
        rl.setLayoutParams(params);

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

        // Set a background for RelativeLayout
        rl.setBackground(getGradientDrawable(color));

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

        // Assign some properties to TextView widget
        tv.setText((getColors()[position]).toUpperCase());
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 85);
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(getDarkerColor(color));

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

        // Draw a shadow around the TextView text
        tv.setShadowLayer(
                15, // radius
                0, // dx
                0, // dy
                Color.WHITE
        );

        // Put the TextView into RelativeLayout
        rl.addView(tv);

        // Put the RelativeLayout to the container
        container.addView(rl);

        // Return the RelativeLayout
        return rl;
    }

    // public void destroyItem (ViewGroup container, int position, Object object)
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((RelativeLayout)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();
        gradient.setGradientType(GradientDrawable.SWEEP_GRADIENT);
        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];
        Color.colorToHSV(color,hsv);
        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];
        Color.RGBToHSV(
                Color.red(color), // Red value
                Color.green(color), // Green value
                Color.blue(color), // Blue value
                hsv
        );
        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 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}
More android examples