Android – Material design tutorial -7 ( NavigationView )

In this tutorial, we will discuss about navigation view. Using Navigation View which was introduced with android design support library, we can create a navigation drawer easily that comply with the Navigation Drawer Design Guideline .

 

navigation

 

Create one project in android studio with activity MainActivity.java and layout resource file for this activity as activity_main.xml
 
NavigationView is added inside DrawerLayout . It contains all the navigation drawer items and one Header view (Top View containing user image, user name and user email )
 
Drawer items and Navigation Header can be loaded into the DrawerLayout manually or programatically.
Manually : Using app:menu and app:headerLayout
Programatically : Using navigationView.inflateHeaderView() and navigationView.inflateMenu()
 
In this example, we are inflating navigation items manually and header programatically.
 
1. We will use Glide for loading and CircleImageView library for user image . i.e. build.gradle dependencies will be like:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:23.2.1'
}
2. Edit your activity_main.xml file as :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

2. Create app_bar_main.xml that will contain the ToolBar

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

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

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

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

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

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

contain_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:background = "#263238"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.codevscolor.navigationviewdemo.MainActivity"
    tools:showIn="@layout/app_bar_main">

</RelativeLayout>

4. Create nav_header_main.xml file for header view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_header"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">


    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/user_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="@dimen/activity_vertical_margin" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/user_image"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:text="Nandan Kaushik"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:text="codevscolor@gmail.com" />

</RelativeLayout>

5. Create one menu xml file activity_main_drawer.xml that will be used by the Navigation View as navigation drawer items.

<?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/nav_camera"
            android:icon="@drawable/ic_menu_camera"
            android:title="Import" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="Gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="Slideshow" />
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="Share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="Send" />
        </menu>
    </item>

</menu>

4. Finally change our MainActivity.java as

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private CircleImageView userImage;
    private RelativeLayout backImage;

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

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //inflate header view
        final View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
     
        userImage = (CircleImageView) headerLayout.findViewById(R.id.user_image);
        backImage = (RelativeLayout) headerLayout.findViewById(R.id.nav_header);

        //load background image and user image using glide
        Glide.with(this).load(R.drawable.me).into(userImage);
        backImage.setBackground(getResources().getDrawable(R.drawable.background));
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
            Toast.makeText(this, "Clicked on camera", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_gallery) {
            Toast.makeText(this, "Clicked on gallery", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_slideshow) {
            Toast.makeText(this, "Clicked on slideshow", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_manage) {
            Toast.makeText(this, "Clicked on tools", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_share) {
            Toast.makeText(this, "Clicked on share", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_send) {
            Toast.makeText(this, "Clicked on send", Toast.LENGTH_SHORT).show();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
  •  we are using navigationView.inflateHeaderView(R.layout.nav_header_main);to inflate the header view nav_header_main.xml
  • MainActivity is implementing NavigationView.OnNavigationItemSelectedListenerand overriding public boolean onNavigationItemSelected(MenuItem item)method, inside which navigation item clicks are handled.
  • We are using Glide library to load the user image Glide.with(this).load(R.drawable.me).into(userImage);

That’s it . You can pull these project from Github Here.

 

Android – Material Design Tutorial -6 ( TabLayout part 2 )

In our previous tutorial, we have learnt how to create a tab layout and linked it with a view pager containing fragments.

We will use the same application that we have created before. (Github link)

1. Tab modes :  We can have two different tab modes of tab layout and this can be changed by using app:tabModeparameter inside our xml layout file.

a) Scrollable Tab Mode : This is the layout that we have used in our previous tutorial. If this mode is set, tabs will be scrollable automatically . app:tabMode="scrollable" is used to achieve this effect.

<android.support.design.widget.TabLayout
           android:id="@+id/tabLayout"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           app:tabMode="scrollable" />

android-material-design-tablayout1

b) Fixed tab mode : If this mode is used, tabs cannot be scrolled. app:tabMode="fixed"is used to enable this effect.

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

android-tablayout-fixedtabs

2. Tab Gravity : Tab gravity means the gravity of tabs inside the layout app:tabGravity=” ”is used to change the gravity of tabs.First Change the application to use only three tabs instead of eight i.e. comment out last five fragments of the adapter inside MainActivity :

//adapter.addFragment(new FragmentFour(), "four");
//adapter.addFragment(new FragmentFive(), "five");
//adapter.addFragment(new FragmentSix(), "six");
//adapter.addFragment(new FragmentSeven(), "seven");
//adapter.addFragment(new FragmentEight(), "eight");

a) Gravity center : Change the  TabLayout of activity_main.xml file as below :

<android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="center" />

Result will be as below :

android-tabLayout-centered

b) Gravity filled : Change app:tabGravity = "fill"to the tab layout of activity_main.xml

android-tablayout-fill

That’s all about Tab Layout. If you have any doubts, please comment below.

 

Android – Material Design Tutorial -5 ( TabLayout part 1 )

Android Design library has brought a number of important material design components to all android 2.1 and higher devices like navigation drawer,  snackbar, tab layout , floating labels,floating action button etc .

In this tutorial , we will create one simple application to understand how to implement material tabs in android.

1. Create one project on Android Studio with an activity MainActivity and activity_main.xml as its layout.

2. Change styles.xml to use AppCompat NoActionBar theme as :

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

3. Change activity_main.xml :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolBar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:title="@string/app_name"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable" />
    </android.support.design.widget.AppBarLayout>

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

4. Create One Fragment FragmentOne with layout fragment_one.xml

public class FragmentOne extends Fragment {


    public FragmentOne() {
        // empty public constructor
    }


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

}

 

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/fragmentOneBack"
    android:layout_height="match_parent">

</ScrollView>

Similarly create seven more fragments as FragmentTwo, FragmentThree,FragmentFour,FragmentFive…etc.

5. Update your colors.xml as below and use different colours on each fragment’s xml files .

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="fragmentOneBack">#4FC3F7</color>
    <color name="fragmentTwoBack">#DCE775</color>
    <color name="fragmentThreeBack">#90A4AE</color>
    <color name="fragmentFourBack">#61a745</color>
    <color name="fragmentFiveBack">#ba68c8</color>
    <color name="fragmentSixBack">#e57373</color>
    <color name="fragmentSevenBack">#ff7043</color>
    <color name="fragmentEightBack">#aed581</color>
</resources>

6. Update your MainActivity :

  • Create one adapter for ViewPager
  • Add fragments to the adapter using addFragment() method .
  • addFragment()method inside the adapter will add the fragment to an ArrayList fragmentList and name of the fragment to a different ArrayList fragmentTitleList
  • set up the tablayout with viewpager using tabLayout.setupWithViewPager(viewPager)
public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;

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

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);

        //create one adapter , add fragments and set the adapter with viewpager
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FragmentOne(), "one");
        adapter.addFragment(new FragmentTwo(), "two");
        adapter.addFragment(new FragmentThree(), "three");
        adapter.addFragment(new FragmentFour(), "four");
        adapter.addFragment(new FragmentFive(), "five");
        adapter.addFragment(new FragmentSix(), "six");
        adapter.addFragment(new FragmentSeven(), "seven");
        adapter.addFragment(new FragmentEight(), "eight");
        viewPager.setAdapter(adapter);

        //setup tab layout with viewpager
        tabLayout.setupWithViewPager(viewPager);

    }

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

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

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

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

        public void addFragment(Fragment fragment, String title) {
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

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

Run this application , result should be look like as below :

android-material-design-tablayout1

You can clone this project from here .

In our next tutorial, we will discuss about different types of customization that can be done with tab layout.

Android – Material design tutorial -4 ( floating label edit text )

Floating label for edit text was introduced with material design library.Initially it acts as hint inside the Edit Text. When user touches the edit text or start entering the text, it moves to the top of the Edit Text with an animation as a floating label.
 

In this tutorial, we will create one login form using floating label edit texts as shown below .

fletext

 
You can pull this project from Github here.
 
TextInputLayout:
This layout was introduced with Design Library and we this is used to wrap around an editText to create a floating label .
Floating label is picked from the “hint” text defined for that editText. 

We also have two more methods “setErrorEnabled(boolean)” and “setError(CharSequence)” to show errors under an EditText .

1. First create one new project on android Studio
2. Include design library in dependencies tab of your project’s build.gradle

compile 'com.android.support:design:23.1.1'

 3. Update your values/styles.xml file

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorControlNormal">@color/colorHint</item>
        <item name="colorControlActivated">@color/floatingColor</item>
    </style>

    <style name="DialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColorPrimary">@color/textColor</item>
        <item name="android:background">@color/colorBack</item>
    </style>
</resources>
4. Update values/strings.xml

<resources>
    <string name="app_name">Login</string>
    <string name="hint_email">Enter Your email</string>
    <string name="hint_password">Enter Password</string>
    <string name="hint_empty">This field cannot be blank</string>
    <string name ="error_email">Please enter a valid email</string>
</resources>

5. Create one Activity “MainActivity”

public class MainActivity extends AppCompatActivity {

    private EditText etEmail;
    private EditText etPassword;
    private Button loginButton;

    private String emailText;
    private String pwdText;

    private TextInputLayout emailLayout;
    private TextInputLayout pwdLayout;

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

        etEmail = (EditText) findViewById(R.id.editTextEmail);
        etPassword = (EditText) findViewById(R.id.editTextPassword);
        loginButton = (Button) findViewById(R.id.button);

        emailLayout = (TextInputLayout) findViewById(R.id.layout_email);
        pwdLayout = (TextInputLayout) findViewById(R.id.layout_password);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });

    }

    private void login() {
        emailText = etEmail.getText().toString().trim();
        pwdText = etPassword.getText().toString().trim();

        if (emailText.isEmpty()) {
            emailLayout.setError(getString(R.string.hint_empty));
        } else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailText).matches()) {
            emailLayout.setError(getString(R.string.error_email));
        } else {
            emailLayout.setErrorEnabled(false);
        }
        if (pwdText.isEmpty()) {
            pwdLayout.setError(getString(R.string.hint_empty));
        } else {
            pwdLayout.setErrorEnabled(false);
        }

        if (!emailLayout.isErrorEnabled() && !pwdLayout.isErrorEnabled()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.DialogStyle);
            builder.setMessage("Successfull !!");
            builder.setPositiveButton("OK", null);
            builder.show();
        }

    }
}

6.Update activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:background="@color/colorBack"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.codevscolor.floatinglabeletdemo.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="@color/colorHint">

        <EditText
            android:id="@+id/editTextEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:textColor="@color/textColor" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/layout_email"
        android:textColorHint="@color/colorHint">

        <EditText
            android:id="@+id/editTextPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="45dp"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:textColor="@color/textColor" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/layout_email"
        android:layout_marginTop="104dp"
        android:background="@color/buttoncolor"
        android:text="Login"
        android:textColor="@color/textColor" />
</RelativeLayout>

Thats all.Clone this project from Github and try to run it on Android Studio. If you are having any problem or if you have any doubt , please let me know 🙂

Android – Material Design Tutorial -3 ( FAB AND SNACKBAR )

  • Floating action button is circle shaped ,floats above the UI ,and also have special motion behaviours 
  • FAB comes in two different sizes. normal(56 dp) and mini(40 dp).
  • Sizes can be changed in the layout file with “fabSize” attribute .
  • By default it takes application’s accent colour for its background .  
  • SnackBar is used to show a quick message to the user at the bottom of the screen.
    On larger devices, it appears on lower left side. Snackbar appears on all other elements and only one can be displayed at a time. They automatically disappears after a particular time interval or if user interacts elsewhere on the screen. 
  • Also we can add an action to the snackbar.
 

In this tutorial, we will create one simple activity with a floating action button and clicking on this will show a SnackBar :

fabsnackbar

1. Create one new project in Android Studio with one activity “MainActivity.java”:

public class MainActivity extends AppCompatActivity {

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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Hello World!!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

}


2.
 Add  activity_main.xml  and content_main.xml  files to your res/layout/ folder :

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

    </android.support.v7.widget.Toolbar>

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email"
        app:fabSize = "normal"
        app:layout_anchor="@id/coordinatorLayout"
        app:layout_anchorGravity="bottom|right|end" />

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

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

3. Change res/values/colors.xml and build.gradle  files as below :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

 

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

4. Change dimens.xml file as :

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
</resources>

Clone this project frome github here and try to run it . Thanks 🙂