How to Implement SnackBar in Android.

Android 5.0 introduced the material design bring the all new design, patterns, widgets and much more. If you not familiar with material design start here.  Here I will talk about SnackBar introduced in Android Material Design. Snack bar is similar android Toast.

Before you can use Snack bar in your Application you need to add following support design dependency

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

Snackbar can also contain  Button, which makes it different from Toast.

Snackbar can be shown as follows consisting a message like Toast.

Snackbar.make(view, "CoderzPassion Snackbar", Snackbar.LENGTH_LONG)
                       .setAction("Action", null).show();

 SnackBar with Button

snackbarwithbutton=Snackbar.make(findViewById(android.R.id.content), "Snackbar with Button", Snackbar.LENGTH_LONG)
                       .setAction("Dismiss", customSnackbarClick)
                       .setActionTextColor(Color.RED);
               snackbarwithbutton.show();

Now Final Code

Layout for MainActivity.java

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/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"
    tools:context=".MainActivity">

<Button
    android:id="@+id/snackbarbutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Snackbar with Button"
    />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/ic_done"
        app:fabSize="normal"
        app:layout_anchor="@id/coordinatorLayout"
        app:layout_anchorGravity="bottom|right|end"/>


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

Code for MainActivity.java

package com.coderzpassion.snackbarsample;

import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button snackbarbutton;
    View.OnClickListener customSnackbarClick;
    Snackbar snackbarwithbutton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        snackbarbutton=(Button)findViewById(R.id.snackbarbutton);
        snackbarbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snackbarwithbutton=Snackbar.make(findViewById(android.R.id.content), "Snackbar with Button", Snackbar.LENGTH_LONG)
                        .setAction("Dismiss", customSnackbarClick)
                        .setActionTextColor(Color.RED);
                snackbarwithbutton.show();
            }
        });


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

         customSnackbarClick=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snackbarwithbutton.dismiss();
            }
        };
    }

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

Output

androidcustomsnackbar    androidsnackbar    workingwithsnackbar

 

Android AppBarLayout like Whatsapp Tutorial/Example

AppBarLayout is a vertical LinearLayout which implements various material design scrolling gestures.if you are not aware of Material Design refer here.

AppBarLayout children should provide scrolling behaviour by setScrollFlags(int) or in XML by app:layout_scrollFlags=””

Note: AppBarLayout depends heavily on being used as a direct child of Coordinator layout if you used with other ViewGroup its most of the scrolling functionality will not work.

So, Lets start:-

  1. Add following dependencies in build.gradle to work with AppBarLayout
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
  2. Create a layout containing AppBarLayout

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:id="@+id/appbar"
        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="wrap_content"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:background="#6495ED"
            />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#6495ED"
            />
    </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>

app:layout_behavior describes the scroll behaviour of view pager it starts scroll below tab layout.

3.Now create a layout for fragment to show items

about.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

4. Now create a layout  for recyclerview items

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:gravity="center_vertical">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardCornerRadius="4dp"
    android:elevation="8dp"
    >
    <TextView
        android:id="@+id/itemname"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="8dp"
        />
    </android.support.v7.widget.CardView>
</LinearLayout>

5.Now create a fragment and adapter for view pager

about.java

package com.coderzpassion.constitution.constitutionofindia;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by coderzpassion on 05/04/16.
 */
public class About extends Fragment {

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

    private void setUpRecyclerView(RecyclerView rv)
    {
        rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));
        rv.setAdapter(new AboutUsAdapter(rv.getContext(), getListForItems()));
    }
    public ArrayList<String> getListForItems()
    {
        ArrayList<String> list =new ArrayList<>();
        list.add("First Item");
        list.add("Second Item");
        list.add("Third Item");
        list.add("Fourth Item");
        list.add("Fifth Item");
        list.add("Six Item");
        list.add("Seven Item");
        list.add("8 Item");
        list.add("9 Item");
        list.add("10 Item");
        list.add("11 Item");
        list.add("12 Item");
        list.add("13 Item");
        list.add("14 Item");
        list.add("15 Item");
        list.add("16 Item");
        list.add("17 Item");
        list.add("18 Item");
        list.add("19 Item");
        list.add("20 Item");
        list.add("21 Item");

        return list;
    }

    public  static class AboutUsAdapter extends RecyclerView.Adapter<AboutUsAdapter.ViewHolder>
    {
        ArrayList<String> aboutlist=new ArrayList<>();
        Context aboutuscontext;

             public static class ViewHolder extends RecyclerView.ViewHolder
             {
                 public final TextView items;
                public ViewHolder(View view)
                {
                    super(view);
                    items=(TextView)view.findViewById(R.id.itemname);
                }
             }

        public AboutUsAdapter(Context context,ArrayList<String> list)
        {
            aboutuscontext=context;
            aboutlist=list;

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
           View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.listitems, parent, false);
            return  new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
                 holder.items.setText(aboutlist.get(position));
        }

        @Override
        public int getItemCount() {
            return aboutlist.size();
        }
    }
}

6.Now create a MainActivity and code for AppBarLayout

MainActivity.java

package com.coderzpassion.constitution.constitutionofindia;

import android.database.DataSetObserver;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;

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

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

        final ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
        ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager);
        if(viewPager!=null)
        {
            setUpViewPager(viewPager);
        }
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
       private void setUpViewPager(ViewPager viewPager)
        {
            Adapter adapter=new Adapter(getSupportFragmentManager());
            adapter.addFragment(new About(),"Article 1");
            adapter.addFragment(new About(),"Article 2");
            adapter.addFragment(new About(),"Article 3");

            viewPager.setAdapter(adapter);
           }
    @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);
    }
    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

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

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

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

Output

appbarlayoutlikewhatsapp    workingwithappbarlayout    makingtoolbarlikewhatsapp

 

 

Android Material Design Floating Labels for EditText Tutorial/Example

Android floating labels were introduced in Android Lollipop’s Material design that completely refreshed the layout.

Floating Labels as the name suggests floats from acting as a hint in EditText to acting as labels to EditText when a user clicks on EditText to type text.

In this tutorial, we will learn how to use Floating labels in the application.Floating labels are implemented with the help of TextInputLayout and EditText.

TextInputLayout was introduced in android support design library to act as floating labels. EditText is wrapped in TextInputLayout and act as a floating label.TextInputLayout takes the value of android:hint set to EditText and display hint as Floating Label.

1.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2. Add following dependencies to your build.gradle to work with Material design and android support design library.

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

3. Create a layout for our main screen that will be our MainActivity.java class.

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_height="match_parent"
    android:layout_width="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/firstname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >
        <EditText
            android:id="@+id/userfname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:hint="Enter First Name"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/lastname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >
            <EditText
                android:id="@+id/userlname"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint="Enter Last Name"/>
        </android.support.design.widget.TextInputLayout>
        <android.support.design.widget.TextInputLayout
            android:id="@+id/age"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >
            <EditText
                android:id="@+id/userage"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint="Enter your age"/>
        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Submit Details"/>
    </LinearLayout>

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

4. Create MainActivity.java and implemet TextInputLabel and EditText to act as Floating Labels

MainActivity.java

package com.coderzpassion.materialfloatinglabelsample;

import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextInputLayout fname,lname,age;
    EditText firstname,lastname,userage;
    Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fname=(TextInputLayout)findViewById(R.id.firstname);
        lname=(TextInputLayout)findViewById(R.id.lastname);
        age=(TextInputLayout)findViewById(R.id.age);

        firstname=(EditText)findViewById(R.id.userfname);
        lastname=(EditText)findViewById(R.id.userlname);
        userage=(EditText)findViewById(R.id.userage);
        submit=(Button)findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               boolean check= checkIfDetailsEmpty();
                if(check)
                {
                    //perform something there like send to profile activity or anything u want
                    //i am just displaying a toast to indicate the user
                    Toast.makeText(MainActivity.this,"Details are successfully submited",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    public boolean checkIfDetailsEmpty()
    {
        if(firstname.getText().toString().equalsIgnoreCase(""))
        {
            fname.setError("Please Enter FirstName");
            firstname.requestFocus();
            return false;
        }
        else
        {
            fname.setErrorEnabled(false);
        }
         if(lastname.getText().toString().equalsIgnoreCase(""))
        {
            lname.setError("Please Enter LastName");
            lastname.requestFocus();
            return false;
        }
         else
         {
             lname.setErrorEnabled(false);
         }
         if(userage.getText().toString().equalsIgnoreCase(""))
        {
            age.setError("Please Enter age");
            userage.requestFocus();
            return false;

        }
         else
         {
             age.setErrorEnabled(false);
         }
        return true;

    }

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

Output

Screen Shot 2016-03-01 at 1.42.29 AM          Screen Shot 2016-03-01 at 1.43.29 AM

Android Material Design FloatingActionButton

In the Previous tutorial Android Working with Material Design, I talked about Material design, how to add ActionBar and create custom themes and using them in our application.

In this tutorial, we will learn about FloatingActionButton which was introduced in Material Design. The FloatingActionButton as the name suggests floats on UI in a circular shape.

Note: Update your Android Studio to the latest version it by defaults set theme containing ActionBar. if you are not aware of adding ActionBar then do visit Android Working with Material Design.

FloatingActionButton has following attributes:

  1. app:fabSize: – it has two sizes one is default size and the second one it has mini size.
  2. app:backgroundTint: – it is used to set a background color for floatingactionbutton
  3. use can use layout_gravity to set floatingactionbutton’s position.

So, Let’s Start.

1.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

 

2.First add following dependencies to your build.gradle to work with Material Design

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

3. Now we will create layout for MainActivity.java class containing FloatingActionButton

activity_main.xml

<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/myfloatingbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
       
        />


</RelativeLayout>

4. Now Create a MainActivity.java class that will be our main screen containing FloatActionButton and handle FloatingActionButton click

MainActivity.java

package com.coderzpassion.materialfloatingsample;

import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    FloatingActionButton floatingActionButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        floatingActionButton=(FloatingActionButton)findViewById(R.id.myfloatingbutton);
        //handle FloatingActionButton Click
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"FloatingActionButton is Clicked",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);
    }
}

AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output

Screen Shot 2016-03-01 at 12.09.54 AM

Android Working With Recycler View

Android RecyclerView is more advanced and flexible version of the listview.  RecyclerView is a container for displaying large sets of data that can be scrolled efficiently. Use RecyclerView when you have large data sets whose elements change at runtime.

In this tutorial, we will create RecyclerView with custom layout  and custom Adapter.

So Let’s Start

  1. .Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.
  2. To use Recycler View in our Project we need to add Following dependencies in build.gradle as follows
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:23.1.1'
        compile 'com.android.support:design:23.1.1'
        compile 'com.android.support:recyclerview-v7:23.1.1'
    }
  3. Now we will make Model class as User.java and declare name, age, interests and getters and setters for variables as follows
    package com.coderzpassion.recyclersample;
    
    /**
     * Created by coderzpassion on 28/02/16.
     */
    public class User {
        private String name,age,interests;
    
        public User()
        {
    
        }
        public User(String name,String age,String interests)
        {
            this.name=name;
            this.age=age;
            this.interests=interests;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public String getInterests() {
            return interests;
        }
    
        public void setInterests(String interests) {
            this.interests = interests;
        }
    }
    

    4. Now we will create layout file for adapter and for each row of recyclerview as

          user_layout.xml

<?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:id="@+id/user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>
    <TextView
        android:id="@+id/user_age"
        android:layout_alignParentRight="true"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/user_interests"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user_name"/>

</RelativeLayout>

5. Now Create CustomAdapter for RecyclerView as follows and override necessary methods

CustomRecyclerAdapter.java

package com.coderzpassion.recyclersample;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by coderzpassion on 28/02/16.
 */
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.MyCustomViewHolder> {

    private List<User> userslist;
    Context con;
    class MyCustomViewHolder extends RecyclerView.ViewHolder
    {
        public TextView name,age,interests;

        public MyCustomViewHolder(View v)
        {
            super(v);
            name=(TextView)v.findViewById(R.id.user_name);
            age=(TextView)v.findViewById(R.id.user_age);
            interests=(TextView)v.findViewById(R.id.user_interests);
        }
    }

    public CustomRecyclerAdapter(Context c,List<User> users)
    {
        this.con=c;
        this.userslist=users;
    }

    @Override
    public MyCustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View usersview= LayoutInflater.from(con).inflate(R.layout.user_layout,viewGroup,false);

        return new MyCustomViewHolder(usersview);
    }

    @Override
    public void onBindViewHolder(MyCustomViewHolder myCustomViewHolder, int i) {
        User user=userslist.get(i);
        myCustomViewHolder.name.setText(user.getName());
        myCustomViewHolder.age.setText(user.getAge());
        myCustomViewHolder.interests.setText(user.getInterests());
    }

    @Override
    public int getItemCount() {
        return userslist.size();
    }
}

6. Now we create a layout for our MainActivity.java which will be our main screen of our app.This layout will contain RecyclerView

activity_main.xml

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myrecyclerview"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

7. RecyclerDivider.java which is as a divider between recycler view elements.

package com.coderzpassion.recyclersample;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by coderzpassion on 28/02/16.
 */
public class RecyclerDivider extends RecyclerView.ItemDecoration {
    private static final int [] Attri=new int[]{android.R.attr.listDivider};

    public static final int HORIZONTAL_LIST= LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST=LinearLayoutManager.VERTICAL;

    private Drawable divider;

    private int ORIENTATION;

    public RecyclerDivider (Context context,int orientation)
    {
        final TypedArray aray=context.obtainStyledAttributes(Attri);
        divider=aray.getDrawable(0);
        aray.recycle();
        setOrientationOFRecylerView(orientation);
    }

    public void setOrientationOFRecylerView(int orient)
    {
        if(orient!= HORIZONTAL_LIST && orient!=VERTICAL_LIST)
        {
            throw new IllegalArgumentException("invalid orientation");
        }
        ORIENTATION=orient;
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if(ORIENTATION==VERTICAL_LIST)
        {
            drawVerticalDivider(c,parent);
        }
        else {
            drawHorizontalDivider(c,parent);
        }
    }

    public void drawVerticalDivider(Canvas c,RecyclerView parent)
    {
        final int left=parent.getPaddingLeft();
        final int right=parent.getWidth()-parent.getPaddingRight();
        final int childCount=parent.getChildCount();
        for (int idx=0;idx<childCount;idx++)
        {
            final View child=parent.getChildAt(idx);
            final RecyclerView.LayoutParams params=(RecyclerView.LayoutParams)child.getLayoutParams();
            final int top=child.getBottom() + params.bottomMargin;
            final int bottom=top+divider.getIntrinsicHeight();
            divider.setBounds(left,top,right,bottom);
            divider.draw(c);
        }
    }
    public void drawHorizontalDivider(Canvas c,RecyclerView parent)
    {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + divider.getIntrinsicHeight();
            divider.setBounds(left, top, right, bottom);
            divider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if(ORIENTATION==VERTICAL_LIST)
        {
            outRect.set(0,0,0,divider.getIntrinsicHeight());
        }
        else
        {
            outRect.set(0,0,divider.getIntrinsicWidth(),0);
        }
    }
}

 

8. Finally, we will create MainActivity.java containing RecyclerView and bound adapter to RecyclerView and implement onItemTouchListner that will be called by clicking RecyclerView Item

MainActivity.java

package com.coderzpassion.recyclersample;

import android.content.Context;
import android.graphics.Movie;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    // list containing dummy data of all users
    private List<User> users=new ArrayList<>();
    // Recycler view
    private RecyclerView recyclerView;
   //CustomRecycler Adapter
    private CustomRecyclerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.myrecyclerview);
        //prepare dummy data for adapter
        prepareDummyData();
        adapter=new CustomRecyclerAdapter(MainActivity.this,users);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        // add divider between Recycler view items
        recyclerView.addItemDecoration(new RecyclerDivider(this,LinearLayoutManager.VERTICAL));
        // bound adapter to recycler view
        recyclerView.setAdapter(adapter);
        // set itemTouchListener for recyclerview
        recyclerView.addOnItemTouchListener(new CustomRecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                User user=users.get(position);
                Toast.makeText(MainActivity.this,user.getName()+" is clicked",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(View view, int position) {
                User user=users.get(position);
                Toast.makeText(MainActivity.this,user.getName()+" is long clicked",Toast.LENGTH_SHORT).show();
            }
        }));
    }
     public void prepareDummyData()
     {
         User user =new User("Ayush","20","playing badminton,snooker");
         users.add(user);
         user=new User("Pardeep","18","playing football,reading");
         users.add(user);
         user=new User("Vibhor","22","playing cricket,reading");
         users.add(user);
         user=new User("Jatin","18","playing games,doing gym");
         users.add(user);
         user=new User("Ankur","19","playing Clash of clan,reading");
         users.add(user);
         user=new User("Ankush","20","playing football,reading");
         users.add(user);
         user=new User("Hemant","21","playing Rugby,watching movies");
         users.add(user);
         user=new User("Harprett","24","playing Handball,chilling with friends");
         users.add(user);
         user=new User("Honey","18","playing football,reading");
         users.add(user);


     }
    @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);
    }
    // creating interface to handle clicks for Recycler view items
    public interface ClickListener
    {
        void onClick(View view,int position);
        void onLongClick(View view,int position);
    }
    public static class CustomRecyclerTouchListener implements RecyclerView.OnItemTouchListener
    {
        private GestureDetector gestureDetector;
        private MainActivity.ClickListener clickListener;

        public CustomRecyclerTouchListener(Context context,final RecyclerView recyclerView,final MainActivity.ClickListener clickListener)
        {
            this.clickListener=clickListener;
            gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener()
            {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                   View child=recyclerView.findChildViewUnder(e.getX(),e.getY());
                    if(child!=null && clickListener !=null)
                    {
                        clickListener.onLongClick(child,recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child=recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
            if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(motionEvent))
            {
                clickListener.onClick(child,recyclerView.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean b) {

        }
    }
}

AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

Output

Screenshot_2016-02-28-23-01-13 Screenshot_2016-02-28-23-01-24 Screenshot_2016-02-28-23-01-21