Tab Layout - Material Design Support Library Tutorial (Sliding Tabs)

With Material Design Support library out and available, Building great looking android apps have become easier for a developers. Today we are going to take a look at building Sliding Tabs in android. I have covered the development of sliding tabs before this library was available in another post which was a little tiresome job, with Material design support library integrating sliding tabs in your layout has now become a piece of cake.


Prerequisites

This tutorial is going to use a toolbar as action bar and if you aren't familiar with building toolbar then before starting out this tutorial please go through that my Toolbar tutorial. This is not absolutely necessary but I strongly recommend you do give it a read.

Secondly I have explained the working of sliding tabs in my previous post before this library was out. I recommend you to give that post a read as well, I don't want you to read the complete tutorial but just the part under
"Understanding The Sliding Tab Layout Implementation"

Requirements

1. Android Studio (latest version recommended)

2. Material Design Support Library (Add the dependency mention below)

compile 'com.android.support:design:22.2.0


Let Us Understand Sliding Tabs/ Tab Layout 




Material design support library provides a class called TabLayout which is basically a view class, required to be added into you layout for creating Sliding Tabs. Most of the times you are going to add this view below your toolbar because thats where you want your Tabs to be placed. Before staring out lets have a look at what we are trying to build up in this tutorial.


As you can see the tabs viz. Home, Inbox, Star are hold by Tab Layout which is placed right below the Toolbar, below the tab layout we have a view pager which is going to be linked with tab layout to achieve the desired effect.


Steps To Build Sliding Tabs With Tab Layout


1. Open Android studio and create a new blank project, after your project has been created go to the res->values folder and create a new file named color.xml. Add the following lines to that file, everything about those colors have been explained in my Toolbar tutorial. The property with name "indicator" is used to define the color of the indicator line below the tabs. which we will set appropriately to the indicator while we code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="PrimaryColor">#2196F3</color>
    <color name="PrimaryDarkColor">#1976D2</color>
    <color name="indicator">#ecd95a</color>

</resources>

2. Now we need to create a state list selector for the tabs text, this state list selector will define the text color of the tabs when they are selected and also define the default text color (When the tab is not the selected tab) So go to res folder and create a new folder named Color. Now create a new file inside this folder and name it tab_selector.xml and add the following lines to that file.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true" android:color="@android:color/white" />
        <item android:state_focused="true" android:color="@android:color/white" />
        <item android:state_pressed="true" android:color="@android:color/white" />
        <item android:color="#d1c9c9" />
</selector>

Here the lines which define the color of text when either selected, focused or pressed are as following

<item android:state_selected="true" android:color="@android:color/white" />
<item android:state_focused="true" android:color="@android:color/white" />
<item android:state_pressed="true" android:color="@android:color/white" />

And the line below defines the default color for the text on tabs.

<item android:color="#d1c9c9" />

3. Now we need to define the style of our app for this project we are only going to define the color properties of our app, you can also define many other properties like text color, text type and font sizes and many more. To do that go to res->values->style.xml and add the following lines to your file. Again all this has been explained previously in my Toolbar tutorial.
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/PrimaryColor</item>
        <item name="colorPrimaryDark">@color/PrimaryDarkColor</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

4. Now time to set up out tabs in our layout go to res->layout->activity_main.xml and add the following lines of code in your file. All we are doing here is basically we are having a relative layout as our root view inside which we are adding Toolbar, below Toolbar we have our Tab Layout and below Tab Layout we have ViewPager. We are setting the background color of the tabs to the primary color which is blue. The same color has been setup for toolbar as well.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#dfdfdf"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/PrimaryColor"
        android:layout_below="@+id/tool_bar"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tabs"
        />

</RelativeLayout>


5. Now lets define how a single tabs content will look like, As you have seen we are not going to do anything fancy we are just having a simple text which says "Hello, This is a tab layout" which is placed in middle of the the screen. So go to res->layout and create a new layout name it tabs.xml and add the following lines of code to it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="This is a tab layout"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

6. Now we are pretty much done with the design part of the app so we can start coding it now. First of all we have added a view pager in the layout so we need to create a fragment which this view pager will hold. We are going to have three tabs but for ease of this tutorial I am only going to create one fragment which this view pager will hold and the same fragment will be shown when the tab changes. obviously you can create new fragment and add different content in them as per your requirement. We have already created the layout for the fragment (tabs.xml) now we need to code it so go to java->[package name] and create a new java class and name it TabFragment.java and add the following lines of code to that file.

package com.android4devs.slidingtabs;

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

/**
 * Created by Admin on 11-12-2015.
 */
public class TabFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tabs, container, false);
    }
}


7. Now as we have a view pager, we need to create an adapter for the view pager, So go to java->[package name] and create a new java class, name it ViewPagerAdapter.java and add the following lines of code to it. [Read the comments in the code bellow to understand whats happening]


package com.android4devs.slidingtabs;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Created by Admin on 11-12-2015.
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        return new TabFragment();    // Which Fragment should be dislpayed by the viewpager for the given position
                                    // In my case we are showing up only one fragment in all the three tabs so we are
                                    // not worrying about the position and just returning the TabFragment
    }

    @Override
    public int getCount() {
        return 3;           // As there are only 3 Tabs
    }
   
}

8. Now we have everything in place to start coding our main activity, so go to java->[package-name]->MainActivity.java and add the following line of code to the file, [Read the comments in the file to understand whats happening]

package com.android4devs.slidingtabs;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    //Declaring All The Variables Needed
    
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        /*
        Assigning view variables to thier respective view in xml
        by findViewByID method
         */
        
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        /*
        Creating Adapter and setting that adapter to the viewPager
        setSupportActionBar method takes the toolbar and sets it as
        the default action bar thus making the toolbar work like a normal
        action bar.
         */
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);
        setSupportActionBar(toolbar);

        /*
        TabLayout.newTab() method creates a tab view, Now a Tab view is not the view 
        which is below the tabs, its the tab itself.
         */
        
        final TabLayout.Tab home = tabLayout.newTab();
        final TabLayout.Tab inbox = tabLayout.newTab();
        final TabLayout.Tab star = tabLayout.newTab();

        /*
        Setting Title text for our tabs respectively
         */
        
        home.setText("Home");
        inbox.setText("Inbox");
        star.setText("Star");

        /*
        Adding the tab view to our tablayout at appropriate positions
        As I want home at first position I am passing home and 0 as argument to 
        the tablayout and like wise for other tabs as well
         */
        tabLayout.addTab(home, 0);
        tabLayout.addTab(inbox, 1);
        tabLayout.addTab(star, 2);
        
        /*
        TabTextColor sets the color for the title of the tabs, passing a ColorStateList here makes
        tab change colors in different situations such as selected, active, inactive etc
        
        TabIndicatorColor sets the color for the indiactor below the tabs
         */
        
        tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
        tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));

        /*
        Adding a onPageChangeListener to the viewPager
        1st we add the PageChangeListener and pass a TabLayoutPageChangeListener so that Tabs Selection
        changes when a viewpager page changes.
         */
        
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        

    }

    @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);
    }
}



9. Now if you run the project you would have a working demo of sliding tabs as shown below.



10. Now many a times you wont be needing text on tabs but you would be needing icons in place of text, Well with the TabLayout thats very easy to add as well. So to get Icons instead of text first of all copy paste your icons into your projects drawable folder, I have downloaded 

ic_home_grey.png,
ic_inbox_grey.png
ic_star_grey.png 

ic_home_white.png
ic_inbox_white.png
ic_star_white.png

grey icon for non selected tab and white for selected tab. I copy pasted all 6 icons in my project

11. Now open up MainActivity and Replace the following line of code

home.setText("Home");
inbox.setText("Inbox");
star.setText("Star");

with the code below

home.setIcon(R.drawable.ic_home_white);
inbox.setIcon(R.drawable.ic_inbox_grey);
star.setIcon(R.drawable.ic_star_grey);

First Icon (Home) is set to white and rest to grey because by default home tab will be selected when app is going to open up.

12. Now I need to change the icons as soon as some other tab is selected by the user, for that we add a onPageListner to the ViewPager and in the method onPageSelected we change the icons appropriately. To do this open up your main activity and add the following code to it. So MainActivity.java for tabs with icon looks something like this.
package com.android4devs.slidingtabs;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    //Declaring All The Variables Needed

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;


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

        /*
        Assigning view variables to thier respective view in xml
        by findViewByID method
         */

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        /*
        Creating Adapter and setting that adapter to the viewPager
        setSupportActionBar method takes the toolbar and sets it as
        the default action bar thus making the toolbar work like a normal
        action bar.
         */
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);
        setSupportActionBar(toolbar);

        /*
        TabLayout.newTab() method creates a tab view, Now a Tab view is not the view
        which is below the tabs, its the tab itself.
         */

        final TabLayout.Tab home = tabLayout.newTab();
        final TabLayout.Tab inbox = tabLayout.newTab();
        final TabLayout.Tab star = tabLayout.newTab();

        //Setting Icons to our respective tabs

        home.setIcon(R.drawable.ic_home_white);
        inbox.setIcon(R.drawable.ic_inbox_grey);
        star.setIcon(R.drawable.ic_star_grey);

        /*
        Adding the tab view to our tablayout at appropriate positions
        As I want home at first position I am passing home and 0 as argument to
        the tablayout and like wise for other tabs as well
         */
        tabLayout.addTab(home, 0);
        tabLayout.addTab(inbox, 1);
        tabLayout.addTab(star, 2);

        /*
        TabTextColor sets the color for the title of the tabs, passing a ColorStateList here makes
        tab change colors in different situations such as selected, active, inactive etc

        TabIndicatorColor sets the color for the indiactor below the tabs
         */

        tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
        tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));

        /*
        Adding a onPageChangeListener to the viewPager
        1st we add the PageChangeListener and pass a TabLayoutPageChangeListener so that Tabs Selection
        changes when a viewpager page changes.
        
        2nd We add the onPageChangeListener to change the icon when the page changes in the view Pager
         */

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        /*
                        setting Home as White and rest grey
                        and like wise for all other positions 
                         */
                        home.setIcon(R.drawable.ic_home_white);
                        inbox.setIcon(R.drawable.ic_inbox_grey);
                        star.setIcon(R.drawable.ic_star_grey);
                        break;
                    case 1:
                        home.setIcon(R.drawable.ic_home_grey);
                        inbox.setIcon(R.drawable.ic_inbox_white);
                        star.setIcon(R.drawable.ic_star_grey);
                        break;
                    case 2:
                        home.setIcon(R.drawable.ic_home_grey);
                        inbox.setIcon(R.drawable.ic_inbox_grey);
                        star.setIcon(R.drawable.ic_star_white);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @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);
    }
}


13. Now If you run the app you would get your app running and it would look like this.



14. So with that we have a working sliding tabs demo with text as well as icons.

Bonus Tip

1. When creating your ViewPagerAdapter.java you can ovverride the getPageTitle(int Positon) method something like following

@Overridepublic CharSequence getPageTitle(int position) {
    switch (position){
        case 0:
            return "Home";
        case 1:
            return "Inbox";
        case 2:
            return "Star";
    }
    return "Default Text";
}

By doing so, your tabs would get title text from this method instead of setting them like

home.setText("Home");
inbox.setText("Inbox");
star.setText("Star");

2. Sometimes you might want to have icons and text or some other wired combination as your tab, well with the new library even thats possible, Lets say I want to have a Icon and TextView Below the icon and I want the TextView Bold well . So all I do is create a new layout file name it custom_view.xml add the following line of code to it

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_horizontal"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>


Now All I need to do is set this layout to the Tabs we created in the MainActivity.xml, lets say I want to set this layout as the tab view to the home tab so I remove setIcon() method and add a setCustomView() method to the tab and this layout gets added to the tab. Now ofcourse you need to inflate the view in a view object something like the following before you set the view to the tabs to have a appropriate icon and text set to all the tabs here is the part of the code you need to add in your main activity


        View HomeView = getLayoutInflater().inflate(R.layout.coustom_view,null);
        ImageView iconHome = (ImageView) HomeView.findViewById(R.id.imageView);
        TextView textView = (TextView) HomeView.findViewById(R.id.textView2);
        iconHome.setImageResource(R.drawable.ic_home_grey);
        textView.setText("Home");

        View InboxView = getLayoutInflater().inflate(R.layout.coustom_view,null);
        ImageView iconIn = (ImageView) InboxView.findViewById(R.id.imageView);
        TextView textViewIn = (TextView) InboxView.findViewById(R.id.textView2);
        iconIn.setImageResource(R.drawable.ic_inbox_grey);
        textViewIn.setText("Inbox");

        View StarView = getLayoutInflater().inflate(R.layout.coustom_view,null);
        ImageView iconStar = (ImageView) StarView.findViewById(R.id.imageView);
        TextView textViewStar = (TextView) StarView.findViewById(R.id.textView2);
        iconStar.setImageResource(R.drawable.ic_inbox_grey);
        textViewStar.setText("Star");

        home.setCustomView(HomeView);
        inbox.setCustomView(InboxView);
        star.setCustomView(StarView);

        tabLayout.addTab(home, 0);
        tabLayout.addTab(inbox, 1);
        tabLayout.addTab(star, 2);

If you run the app with the above changes here is the result you would get



So we have a icon and textview below it and a bold style to text view as we wanted, So that wraps the TabLayout in the Material design support library. 

 I dont know if you can call this as a tip but thats a option available while working with the TabLayout as a blogger providing tutorials I want reader to know all that I understand. Hope you like the tutorial, Subscribe to mail list and Keep Coding.

Navigation View - Material Design Support Library Tutorial

Few days back Google announced Material Design Support Library in their Google IO 2015, and today we are going to take a look at one of the component of the material design library and that's Navigation View,  Navigation View makes it very easy to make a good looking material design Navigation drawer, I have showed you how to make a navigation drawer before this library came out and it was pretty tiresome but with this library things have changed.  So Lets get started


Prerequisites

Tutorial is going to use a toolbar as action bar and if you aren't familiar with building toolbar then before starting out this tutorial please go through that my Toolbar tutorial. This is not absolutely necessary but I strongly recommend you do give it a read.

Requirements

1. Android Studio  1.3 (Version used for this tutorial)

2. Circle Image Library (Add the dependency mentioned below)

compile 'de.hdodenhof:circleimageview:1.3.0'

3. Material Design Support Library (Add the dependency mention below)

compile 'com.android.support:design:22.2.0

In my previous tutorial I have explained how the DrawerLayout works which will act as our root view in this tutorial so if you are not sure about its working just go and read that particular section from that tutorial, The link to that tutorial is here - 

Lets Understand Navigation View




Think of NavigationView as any other view you know, Navigation View has two main components which you can define according to your requirements those component are as show

Header View
This View is basically the top part of the navigation drawer, which holds the profile picture, name and email etc. You need to define this in a separate layout file we would look into that in just a moment.

 Menu
This is the menu you want to show below your header, we define menu in a menus folder, just like you define menu for your overflow menu.
So basically NavigationView is a container for the Header View and Menu which you are going to use in your sliding drawer. So now that you understand the NavigationView we can start building our Navigation Drawer.

So before we start building our app lets take a look at what we are trying to build, look at the gif below and you can see that we are going to make a sliding navigation drawer also on clicking inbox option you see we open the Inbox fragment inside the app, when you click any other option we show toast message indicating we have received the click event


Steps To Build Navigation Drawer With Navigation View


1. Open Android Studio and create a new blank project, Once your project is created go ahead and define Color scheme for your app. You do that by creating a file called colors.xml in res -> values  folder of your project. Now go ahead and add this lines to your color file again all about those colors and their usage explained in my Toolbar tutorial.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="PrimaryColor">#2196F3</color>
    <color name="PrimaryDarkColor">#1976D2</color>
</resources>


2.  Now we define style for our app, Go ahead and open the styles.xml file of your project located at res -> values folder . Add the following line to the styles.xml. We are setting the color scheme for the entire app notice we make our status bar color transparent. As to achieve the desired results.
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:colorPrimary">@color/PrimaryColor</item>
        <item name="android:colorPrimaryDark">@color/PrimaryDarkColor</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
        <!-- Customize your theme here. -->
    </style>
</resources>


3. Now lets first define how our header in the navigation drawer would look like, for this go ahead and create a new layout resource file in your layouts folder and name it header.xml. Add the following code to the file. Our header layout has Relative layout with three views inside it  one Circle Image View for the profile picture and two text views one for Name and other for email. I have added the Image named profile to my drawable folder to use it with Circle Image View.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="190dp"
    android:background="@drawable/background_material"
    android:orientation="vertical"
    >

    <de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="76dp"
    android:layout_height="76dp"
    android:src="@drawable/profile"
    app:border_color="#FF000000"
    android:layout_marginLeft="24dp"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginStart="24dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Akash Bangad"
        android:textSize="14sp"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:gravity="left"
        android:paddingBottom="4dp"
        android:id="@+id/username"
        android:layout_above="@+id/email"
        android:layout_alignLeft="@+id/profile_image"
        android:layout_alignStart="@+id/profile_image" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Akash.bangad93@gmail.com"
        android:id="@+id/email"
        android:gravity="left"
        android:layout_marginBottom="8dp"
        android:textSize="14sp"
        android:textColor="#fff"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/username"
        android:layout_alignStart="@+id/username" />

</RelativeLayout>

4. Now with our header view done lets make our menu, for that go to res -> menu and create a new menu resource file and name it drawer.xml and add the following code to your file. Every menu option is enclosed withing <item> tag we have grouped them together with <group> tag setting  android:cheakableBehavour=”single” makes sure only one item can be selectable at once. Icon Tag indicate the icon we want the menu items to show besides them  I have downloaded my icons from 
www.google.com/design/icons and added them to my drawable folder.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/inbox"
            android:checked="false"
            android:icon="@drawable/ic_inbox_black"
            android:title="@string/inbox_string" />

        <item
            android:id="@+id/starred"
            android:checked="false"
            android:icon="@drawable/ic_star_black"
            android:title="@string/starred_string" />

        <item
            android:id="@+id/sent_mail"
            android:checked="false"
            android:icon="@drawable/ic_send_black"
            android:title="@string/sent_mail_string" />

        <item
            android:id="@+id/drafts"
            android:checked="false"
            android:icon="@drawable/ic_drafts_black"
            android:title="@string/draft_string" />


        <item
            android:id="@+id/allmail"
            android:checked="false"
            android:icon="@drawable/ic_email_black"
            android:title="@string/all_mail_string" />
        <item
            android:id="@+id/trash"
            android:checked="false"
            android:icon="@drawable/ic_delete_black"
            android:title="@string/trash_string" />
        <item
            android:id="@+id/spam"
            android:checked="false"
            android:icon="@drawable/ic_error_black"
            android:title="@string/spam_string" />

    </group>
</menu>

5. Now with our header and menu created we can start creating our main_activity.xml, so open up main_activity.xml  and add the following code inside it. As you can see we have our DrawerLayout root view and it has two child view, the first one represents the content of our app which is linear layout in my case I have added my toolbar and frameLayout inside the linear layout. Now the second child of our Drawer Layout is going to be the view which we want to act like a sliding drawer in our case its the Navigation View. Rhe following attributes help us link our drawer menu and header view to navigation view. Setting gravity start makes the view slide from left. Also notice that we have added
android:fitsSystemWindows="true" attribute to our drawerlayout to achieve the slide under transparent status bar effect.
app:headerLayout="@layout/header" 
app:menu="@menu/drawer"
android:layout_gravity="start"
rest of the code is self explanatory.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical"
        >
        <include
            android:id="@+id/toolbar"
            layout="@layout/tool_bar"
        />
        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/drawer"
        />
</android.support.v4.widget.DrawerLayout>


6. Now for the purpose of tutorial I am going to make a fragment and show you how to replace the fragment with the contents of your app when your menu item in drawer is selected so go ahead and create a layout for the fragment I have named mine content_fragment.xml. Add the following code to it (Just a TextView Inside a relative layout).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="INBOX"
        android:padding="8dp"
        android:textColor="#fff"
        android:background="@color/PrimaryColor"
        android:textSize="28sp"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>



7.  Now go to Java->[app_package_name] and create a new class for your fragment name. I have named mine ContentFragment. Add the following lines of code. Code is pretty self explanatory, with that we have our fragment ready.
package com.android4dev.navigationview;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Admin on 04-06-2015.
 */
public class ContentFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.content_fragment,container,false);
        return v;
    }
}


8. Now finally go to MainActivity.xml add Add the following code, I have added Comments to help you understand the code so make sure you read the comments.
package com.android4dev.navigationview;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //Defining Variables
    private Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;

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

        // Initializing Toolbar and setting it as the actionbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        //Initializing NavigationView
        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            
            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                
                //Checking if the item is in checked state or not, if not make it in checked state
                if(menuItem.isChecked()) menuItem.setChecked(false);
                else menuItem.setChecked(true);

                //Closing drawer on item click
                drawerLayout.closeDrawers();
                
                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()){

                    
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.inbox:
                        Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
                        ContentFragment fragment = new ContentFragment();
                        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.frame,fragment);
                        fragmentTransaction.commit();
                        return true;
                   
                    // For rest of the options we just show a toast on click
                    
                    case R.id.starred:
                        Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.sent_mail:
                        Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.drafts:
                        Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.allmail:
                        Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.trash:
                        Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.spam:
                        Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
                        return true;
                    default:
                        Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
                        return true;

                }
            }
        });

        // Initializing Drawer Layout and ActionBarToggle
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawerLayout.setDrawerListener(actionBarDrawerToggle);
        
        //calling sync state is necessay or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();






    }

    @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);
    }
}


9. So with that we are done,  If you follow the tutorial properly and now if you run the app you would get the desired result as shown below.



This concludes the tutorial hope you learned something and you like it, If you do like it please share, comment and subscribe for more tutorials.

How To Make Floating Action Button (FAB) - Material Design Tutorial

In this tutorial, we are going to learn how to implement the Floating Action Button (a.k.a FAB) which is one of the newest component brought into android with the introduction of material design. Floating Action Button is the button which prompts the main task of your application and is not compulsory to add FAB to your app if you want to avoid the FAB you are free to do that as well, FAB as said earlier is used to access the main task of the app for example a video player app will use FAB to play the videos, Social network app will use the FAB to post status, photos etc. With all that explained let's begin the tutorial.

Prerequisites


To Demonstrate how to make the Floating Action Button, I would be using the Toolbar project I made previously, you can check the Toolbar project here. If you are already aware of building toolbar then you can directly jump into the project.

To implement the Floating Action Button (FAB) from scratch we would be building a custom drawable, it is required that you understand how drawable works in android, especially layer-list. If you are not familiar with drawables don't worry I would be explaining as much as I can.

Requirments

Android Studio 1.0.1 (Version I am using)

Icon for the FAB

That's it, noting else.


Let's Understand How the Floating Action Button (FAB) Can Be Implemented




I would be showing you two ways of building Floating Action Button.

1. Building FAB from scratch with custom drawable.

2. Building FAB from available libraries and best FAB libraries.  (Coming soon)

Using libraries is the simplest way and as you are always going to need the FAB from now on you should probably get familiar with one of the library and start implementing FAB with it. 

But sometimes when you have very specific need and you need complete control over your FAB then you have to build it from scratch.


Building Floating Action Button From Scratch with custom drawables.

So for making a custom FAB follow the steps as shown below. after you complete the following steps your result would look something like this. 



Step 1. Start android studio, create a new blank project. Now before we do anything we need to first make custom circle shape drawable. to do that, go to  res ->  drawable right-click and create a new drawable resource and name it circle.xml. Now in the newly created file add the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:top="8px">
        <layer-list>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#08000000"/>
                    <padding
                        android:bottom="3px"
                        android:left="3px"
                        android:right="3px"
                        android:top="3px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#09000000"/>
                    <padding
                        android:bottom="2px"
                        android:left="2px"
                        android:right="2px"
                        android:top="2px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#10000000"/>
                    <padding
                        android:bottom="2px"
                        android:left="2px"
                        android:right="2px"
                        android:top="2px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#11000000"/>
                    <padding
                        android:bottom="1px"
                        android:left="1px"
                        android:right="1px"
                        android:top="1px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#12000000"/>
                    <padding
                        android:bottom="1px"
                        android:left="1px"
                        android:right="1px"
                        android:top="1px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#13000000"/>
                    <padding
                        android:bottom="1px"
                        android:left="1px"
                        android:right="1px"
                        android:top="1px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#14000000"/>
                    <padding
                        android:bottom="1px"
                        android:left="1px"
                        android:right="1px"
                        android:top="1px"
                        />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">
                    <solid android:color="#15000000"/>
                    <padding
                        android:bottom="1px"
                        android:left="1px"
                        android:right="1px"
                        android:top="1px"
                        />
                </shape>
            </item>

        </layer-list>
    </item>

    <item >

        <ripple xmlns:android="http://schemas.android.com/apk/res/android"
            android:color="?android:colorControlHighlight">
            <item android:id="@android:id/mask">
                <shape android:shape="oval">
                    <solid android:color="#FFBB00" />
                </shape>
            </item>
            <item>
                <shape android:shape="oval">

                    <solid android:color="@color/ColorPrimary" />


                </shape>
            </item>
        </ripple>

    </item>


</layer-list>

Now what we have done in the above xml drawable is we have created structure like this.

<layer-list>
      <Item>
                <layer-list>
                 
                 <item> (Layer of shadow)
                 <item>
                 <item>
                 <item>
                   .....
                </layer-list>
       </Item>
       
         <Item>
         
                 <shape> (Oval shape)
                 </shape>

       </Item>

<layer-list>






we have created the drawable by defining layers the root layer consists of 2 items

1. layers of shadows
2. circular shape;

You must notice that the circular shape is enclosed in a ripple tag this tag ensures the circle reacts to on touch with the ripple effect on lollipop devices.

Now if you set the circle.xml as background of any view it will form a cirlce. we are going to use this circle as background to image-button view.

Step 2. Now go to res -> layout right-click and select create a new layout resource, name it tool_bar.xml and the add the following code to that file. (Everything about toolbar is explained in my previous posts )

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

<android.support.v7.widget.Toolbar
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:elevation="2dp"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Dark"
    android:background="@color/ColorPrimary"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Step 3. Now go to res -> values create a new resource file name it colors.xml and add the following code.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>
</resources>

Everything about colors is explained in previous posts, make sure you go through it if you dont understand.

Step 4. Now go to activity_main.xml and add the following code to it. also make sure you add the icon which you want to show inside your FAB to your project. I have downloaded the icon from www.icons4android.com and named it ic_action, and added it to the drawables folder of the project
<RelativeLayout 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"
    tools:context=".MainActivity">

    <include
        android:id="@+id/toolbar"
        layout="@layout/tool_bar"

        ></include>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:id="@+id/frameLayout">

        <TextView
            android:id="@+id/TextAct1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:text="This is the first Activity, Say Hi"
            android:textSize="25dp" />

        <ImageButton
            android:layout_margin="15dp"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/ic_action"
            android:background="@drawable/circle"
            android:id="@+id/imageButton"
            android:layout_gravity="right|bottom" />


    </FrameLayout>
</RelativeLayout>

The structure of activiy_main.xml is pretty self explanatory. There is a FrameLayout inside a RelativeLayout, also inside the frame layout I have added a Text View and an ImageButton. Notice that the background of imageButton is set to "@drawable/circle", width and height of the imageButton is same to make it form into a circle and src of imageButton is set to "@drawable/ic_action" which the icon I have downloaded and added to my project.

Step 5. Now go to your MainActivity.java and add the following code to it.

package com.example.hp1.floatingactionbuttonfab;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    Toolbar toolbar;
    ImageButton FAB;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FAB = (ImageButton) findViewById(R.id.imageButton);
        FAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                
                Toast.makeText(MainActivity.this,"Hello Worl",Toast.LENGTH_SHORT).show();
                

            }
        });
    }


    @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);
    }
}




So If you run your app at this stage you would get something like this.



Pretty good, When you click on the FAB a toast message appears saying "Hello World". But we want some action to be performed when the user clicks the Floating Action Button, just to keep the tutorial simple I am going to start a new activity when the FAB is clicked. So let's start with that now.

Step 6. Go to java -> [package-name]  right-click and select new -> activity -> blank activity give your activity name as SecondActivity and layout name as activity_second.xml. now go to activity_second.xml and add the following code to it.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >


    <include
        android:id="@+id/toolbar"
        layout="@layout/tool_bar"

        ></include>

    <LinearLayout
        android:layout_below="@id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="10dp"
            android:textColor="#000000"
            android:textSize="25dp"
            android:layout_width="242dp"
            android:layout_height="wrap_content"
            android:text="Enter Your Details"
            android:id="@+id/details"
            android:layout_gravity="center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Name"
            android:layout_marginLeft="100dp"
            android:id="@+id/Name"
           android:textSize="20dp"
             />

        <EditText
            android:layout_marginLeft="100dp"

            android:layout_marginTop="5dp"
        android:layout_height="25dp"
            android:layout_width="150dp"
        android:id="@+id/editname" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Address"
            android:layout_marginLeft="100dp"
            android:id="@+id/Address"
            android:textSize="20dp"
            />

        <EditText
            android:layout_marginLeft="100dp"

            android:layout_marginTop="5dp"
            android:layout_height="25dp"
            android:layout_width="150dp"
            android:id="@+id/editadd" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="Phone "
            android:layout_marginLeft="100dp"
            android:id="@+id/phone"
            android:textSize="20dp"
            />

        <EditText
            android:layout_marginLeft="100dp"

            android:layout_marginTop="5dp"
            android:layout_height="25dp"
            android:layout_width="150dp"
            android:id="@+id/editphone" />

        <Button
            android:layout_marginLeft="130dp"
            android:layout_marginTop="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Save"
            android:id="@+id/save" />

    </LinearLayout>
</RelativeLayout>

Now for the purose of the tutorial I have added some random text and edit boxes to the second activity. I have also included a toolbar in this activity as well

Step 7. Go to SecondActivity.java and add the following code to it.
package com.example.hp1.floatingactionbuttonfab;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class SecondActivity extends ActionBarActivity {

    Toolbar toolbar;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }


    @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_second, 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);
    }
}
Nothing much happening here, just initializing the toolbar for the second activity.

Step 8. Now just go to the MainActivity and replace the Code where we made the toast saying "hello world" on click of Floating Action button to the code as shown below.
 

package com.example.hp1.floatingactionbuttonfab;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;


public class MainActivity extends ActionBarActivity {

    Toolbar toolbar;
    ImageButton FAB;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FAB = (ImageButton) findViewById(R.id.imageButton);
        FAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(i);



            }
        });
    }


    @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);
    }
}


As you can see we have added a intetnt to start the new activity, now when you run the app you would get results as you had seen at the start of this tutorial



Thats it, Thats how you implement the FAB with custom drwable.  In the next post I would be providing you with the best Floating Action Button ( FAB ) libraries which you could use in your next project also I have recieved requests from visitors asking for the downloadable projects so starting from this tutorial I am also providing you with downloadable project. if you like this post please comment, subscribe and share

To Download The Project - Click Here


How To Make Material Design Sliding Tabs

In this tutorial we are going to implement sliding tabs in material design style by using the SlidingTabLayout from Google iosched app, The SlidingTabLayout is also provided on the Google developer page as well but it isn't updated with some methods such as setDistributeEvenly() and this method is actually needed to make fixed tabs, the Google ioshed version is more updated and so we are going to use that. Along with the SlidingTabLayout.java we would be needing the SlidingTabStrip.java, Okay so let's start making the Sliding Tabs.


Requirements


1. Android Studio 1.0.1 (latest)

2. SlidingTabLayout.java & SlidingTabStrip.java from IOsched Google App and copy past both the files in your project

Understanding Sliding Tab Layout Implementation





As you can see we have we have made the Linear Layout as the root element for our activity and made the orientation of the LinearLayout as vertical so the elements would be placed one after another, First I have added the toolbar on which I have already made a separate tutorial on how to make a material design toolbar, Next element that I have added is the SlidingTabLayout which acts like a Tab Strip, you can place this strip anywhere in your layout but I want it to be above the pages that are being swiped so I am placing it just below the Toolbar, Next you add the View Pager which is required for swiping the pages. In the code you define every view and then set the SlidingTabs.SetViewPager method to the ViewPager in your activity which is where you tell the app that on page swipe of your View Pager you want the tabs to swipe and change as well.



Steps To Implement Sliding Tab Layout


1. First let's decide the color scheme for our app I want the color scheme to be red so lets do that by making a new color.xml file in your values folder and add the following code to it. You may notice a item in the color.xml with name ScrollColor that is the color which I am going to set to the scroll bar of the Tab Strip.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#e62117</color>
    <color name="ColorPrimaryDark">#c31c13</color>
    <color name="tabsScrollColor">#8a140e</color>

</resources>


2. Next we need to make a layout file for toolbar and add that layout file to our apps activity_main.xml. So create a new layout file and name it tool_bar.xml and add the following code to it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="@color/ColorPrimary"
    android:elevation="2dp"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Dark"
    xmlns:android="http://schemas.android.com/apk/res/android" />

3. Now its time to add Toolbar and the SlidingTabLayout to our main_activity.xml, To add SlidingTablayout in your app you must make sure you have already added the SlidingTabLayout.java and SlidingTabStrip.java in your app as explained in the requirements section at the top. If you have added both the files in your project, open your main_activity.xml and add the following code to it. I have given the SlidigTabLayout an id ="Tabs" and added a elevation of 2dp for the shadow effect.

<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"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

    <com.android4devs.slidingtab.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"/>

</LinearLayout>  

4. Now we just have to add the ViewPager view to your layout, make sure to give it an Id, I have given my ViewPager an Id called pager. Finally your main_activiy.xml looks something like this.

<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"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

    <com.android4devs.slidingtab.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"

        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        ></android.support.v4.view.ViewPager>



</LinearLayout>

5. Now I have decided to make 2 tabs for this project, so I have to make the layout for this tabs, so I have created two new layouts tab_1.xml and tab_2.xml and added the medium text view inside both the layout as shown below.

tab_1.xml


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


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 1"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

tab_2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 2"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Now I am done with my layout section and its time to work things out in the code.

6. Now let's first make the 2 fragments for Tab1 and Tab2, So go ahead and create two new java files, name it Tab1 and Tab2 and add the following code to it.

Tab1


package com.android4devs.slidingtab;

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

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);
        return v;
    }
}


Tab2


package com.android4devs.slidingtab;

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

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_2,container,false);
        return v;
    }
}


7. Now before we start working with MainActiviy we need a ViewPager adapter to provide the views for every page i.e every Tab. So go ahead and make a new java file, name it ViewPagerAdapter and add the following code to it. I have added the comments to help you understand the working.

package com.android4devs.slidingtab;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Created by hp1 on 21-01-2015.
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {

        if(position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;
        }
        else             // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
        {
            Tab2 tab2 = new Tab2();
            return tab2;
        }


    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}


8. Now we have everything ready to start work with the MainActivity.java, So go ahead and add the following code to your MainActivity.java. check out the comments in the code to understand the working.

package com.android4devs.slidingtab;

import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity {

    // Declaring Your View and Variables

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Home","Events"};
    int Numboftabs =2;

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


        // Creating The Toolbar and setting it as the Toolbar for the activity

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);



    }


    @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);
    }
}


Now everything is set, Lets just run our app and check out how it looks



Its Looks perfect. Tabs are working nicely. But what if you want to customize the text color of your Tabs Title for a specific event i.e on Page selected etc and you surely would like to tell the user about the active tab he is on. For this you have to make a selector.xml in  your res/color/ folder and add the following code to your selector.xml, of course change the colors as your requirements

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@android:color/white" />
    <item android:state_focused="true" android:color="@android:color/white" />
    <item android:state_pressed="true" android:color="@android:color/white" />
    <item android:color="#8a140e" />
</selector> 

After making the selector you have to add it in your SlidingTabLayout.java, Look for a method called  private void populateTabStrip() and add the following line of code at the end of it.

tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
tabTitleView.setTextSize(14);


Look at the SlidingTabLayout code below, I have just copy pasted populateTabStrip() method in which you are suppose to do the changes

private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
            tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
            tabTitleView.setTextSize(14);
        }
    }


Finally, Everything is set and we are done. Let's just run the app and check out how things work.



Well that's just looks amazing, So with this you have learned how to make Sliding Tabs in Material Design style, If you like this tutorial please subscribe to the blog for coming updates.