Saturday, July 25, 2015

Navigation View - Support Design Library

In our previous tutorial about Navigation Drawer we saw how to create a navigation drawer using RecyclerView. Before Support Design Library was introduced we had to create navigation drawer using RecyclerView or ListView. We saw in two part series of the tutorial, how much work needed to create a Navigation drawer. It included the setting up adapter, creating different view types and implementing our own listener for selecting Menus.





NavigationView from Design Support Library comes really handy when we want to add Navigation Drawer to our app. Let's create a Navigation Drawer using NavigationView like the screenshot below.




Let's create an Android project with Blank Activity template and add a Toolbar, We will be using Toolbar instead of Actionbar so in values/styles.xml use theme with NoActionbar. Set toolbar as the actionbar of Mainactivity. So MainActivity.java looks like this.



public class MainActivity extends AppCompatActivity {

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


}


Since we will be using NavigationView from Design Support Library, let's at that to the dependencies. Open build.gradle file from app module and add following lines.
OR you can just select the project and hit f4 to open the Project Structure dialog and select dependencies tab , click plus icon at the bottom select library dependency and search recyclerview and select the following library from the list to include it.


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





Best thing about NavigationView is that we don't have to create layouts for each menu item as it uses our existing menu system. if you already have created new android project, let's add a menu called menu_nav_drawer.xml.


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_inbox"
        android:orderInCategory="100"
        android:title="@string/inbox"
        android:icon="@drawable/inbox"
        app:showAsAction="never" />
    <item
        android:id="@+id/menu_send"
        android:orderInCategory="200"
        android:title="@string/send"
        android:icon="@drawable/send"
        app:showAsAction="never" />

</menu>



We just created two menu items, Inbox and Send, If you need icons for them, please download from here.

Next, we create layout for Main activity, in change activity_main.xml as below.


<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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/abc_action_bar_default_height_material"
        android:background="#00bbff"/>



    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/appBar">
        <!--Content-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/app_name" />

        </LinearLayout>

        <!-- Navigation Drawer-->
        <android.support.design.widget.NavigationView
            android:id="@+id/navigationView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:menu="@menu/menu_nav_drawer"
            android:layout_gravity="left"/>

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

</RelativeLayout>

Here, we are using a LinearLayout for our content with a TextView in it. And for Navigation drawer we are using NavigationView.

In navigation we can set up the menu using menu attribute.  We assigned the menu that we created in XML.


            app:menu="@menu/menu_nav_drawer"


Now if you run the project you will see navigation drawer is all set with menu titles and icons





Now Let's add the ActionbarDrawerToggle to add nice icons.


        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);


        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close);

        mDrawerLayout.setDrawerListener(drawerToggle);
        drawerToggle.syncState();



Now finally let's add Listener to the menu items.


             mNavigationView.setNavigationItemSelectedListener(
                        new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.menu_inbox) {
                    Toast.makeText(MainActivity.this, 
                                  "Selected Inbox", 
                                  Toast.LENGTH_SHORT).show();
                    mDrawerLayout.closeDrawer(mNavigationView);
                }
                return false;
            }
        });



Finally add a header view. For that just create a layout and use addHeaderView method on NavigationView.



       View view = getLayoutInflater().inflate(R.layout.layout_drawer_header, 
                   mNavigationView, false);

        mNavigationView.addHeaderView(view);






We saw how Support Design Library made it very easy to create a navigation drawer.


Navigation Drawer using RecyclerView Part - 2

In Part 1, we created a navigation drawer without header. Now it's time to setup the header and click events.




For adding header we can use different item types for our RecyclerView Items. We will use different layout for the header item and the menu items.

Let's have a look at our Adapter code, if you see the   onCreateViewHolder   method, you can see there is second parameter called itemType. That's what determines what layout to use during the view holder creation.

Let's start by creating layout for our header view.


<?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:layout_height="200dp"  
   android:background="@drawable/headerbg">  
   <TextView  
     android:id="@+id/headerText"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textColor="@android:color/white"  
     android:layout_gravity="center"  
     android:paddingTop="100dp"  
     android:textSize="20sp"  
     android:text="Header"/>  
 </LinearLayout> 

Here we added just a textview to header and background image. You can download image from here.


Then, define our view types in our Adapter class. We will have two item types as follows.


   public final static int TYPE_HEADER = 0;  
   public final static int TYPE_MENU = 1; 

Since the LayoutManager needs to know how menu items the RecyclerView has,  add 1 to the getCount method as we are adding a headerView.


   @Override  
   public int getItemCount() {  
     return drawerMenuList.size()+1;  
   }  

And, let the LayoutManager know which item type is the header. We can do so by overriding getItemViewType method. We will have TYPE_HEADER at position 0 and rest of the items will be TYPE_MENU.


  @Override  
   public int getItemViewType(int position) {  
     if(position == 0){  
       return TYPE_HEADER;  
     }  
     return TYPE_MENU;  
   }  

Next we change our onCreateViewHolder class to have to different layouts based on view type.



  @Override  
   public DrawerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
     View view;  
     if(viewType == TYPE_HEADER){  
       view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_drawer_header, parent, false);  
     }else{  
       view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_menu_item, parent, false);  
     }  
     return new DrawerViewHolder(view, viewType);  
   }  

Here, we used layout_drawer_header for header type and layout_menu_item for normal menu items.
We also changed the constructor of DrawerViewHolder to accept the viewType as second parameter. So modify ViewHolder as below.


 class DrawerViewHolder extends RecyclerView.ViewHolder{  
     TextView title;  
     TextView headerText;  
     ImageView icon;  
     public DrawerViewHolder(View itemView, int viewType) {  
       super(itemView);  
       if(viewType == 0){  
         headerText = (TextView)itemView.findViewById(R.id.headerText);  
       }else {  
         title = (TextView) itemView.findViewById(R.id.title);  
         icon = (ImageView) itemView.findViewById(R.id.icon);  
       }  
     }  
   }  


Then, change onBindViewHolder method as below for setting up some Text to the TextView.


  @Override  
   public void onBindViewHolder(DrawerViewHolder holder, int position) {  
     if(position == 0) {  
       holder.headerText.setText("Header Text");  
     }else{  
       holder.title.setText(drawerMenuList.get(position - 1).getTitle());  
       holder.icon.setImageResource(drawerMenuList.get(position - 1).getIcon());  
     }  
   } 

Here we are using "position-1" to access the menu list items that's because we have added the header in the first position so the positions of the menu list and the adapter are not in sync.

And that's all, run the project and see we have a header on top of the menu items.



Finally, add click events to the menu items. For this let's write an OnItemSelectedListener interface with a method onItemSelected.


public interface OnItemSelecteListener{  
     public void onItemSelected(View v, int position);  
   } 

Then create a setOnClicklistener method in the adapter which will help us to set Listener from MainActivity. Create a field mListener of type OnItemSelecteListener and write following method.



public void setOnItemClickLister(OnItemSelecteListener mListener) {  
     this.mListener = mListener;  
   }  

Modify, DrawerViewHolder adding OnClickListener to the itemView so that whenever the itemView is clicked we can pass the clicked position through onItemSelectedMethod.


class DrawerViewHolder extends RecyclerView.ViewHolder{  
     TextView title;  
     TextView headerText;  
     ImageView icon;  
     public DrawerViewHolder(View itemView, int viewType) {  
       super(itemView);  
       if(viewType == 0){  
         headerText = (TextView)itemView.findViewById(R.id.headerText);  
       }else {  
         title = (TextView) itemView.findViewById(R.id.title);  
         icon = (ImageView) itemView.findViewById(R.id.icon);  
       }  
       itemView.setOnClickListener(new View.OnClickListener() {  
         @Override  
         public void onClick(View view) {  
           mListener.onItemSelected(view, getAdapterPosition());  
         }  
       });  
     }  
   }  

Set OnItemSelectedListener to the adapter form activity to perform various actions when menu items are selected. For now let's just show the Toasts. (Be careful about the positions if you have additional types added, for example now we have a header type added so we will have first menu at position 1 instead of 0)



 adapter.setOnItemClickLister(new DrawerAdapter.OnItemSelecteListener() {  
       @Override  
       public void onItemSelected(View v, int position) {  
         Toast.makeText(MainActivity.this, "You clicked at position: "+ position, Toast.LENGTH_SHORT).show();  
       }  
     }); 

Let's run the project.





We built navigation drawer using RecyclerView. You can find the full source code for this tutorial on github.



Navigation Drawer using RecyclerView Part - 1

In the previous tutorial we built a list of android versions using recycler view. Now, since we know how RecyclerView works, let's make a Navigation Drawer using RecyclerView.





So our goal is to build up a navigation drawer like this screenshot. We will be using DrawerLayout for holding our content and RecyclerView for the navigation drawer.






In Part 1 of this tutorial, We will set up the menu and will add header and click events in next part.


Let's start with creating Android project with a blank Activity template. We will have an Activity with a layout XML file ready for our main screen.

First thing first, let's first include the required libraries for our project. Since RecyclerView is a part of support library let's add it to the dependency. For adding the dependency open build.gradle file in the app module and add following dependency. 

OR you can just select the project and hit f4 to open the Project Structure dialog and select dependencies tab , click plus icon at the bottom select library dependency and search recyclerview and select the following library from the list to include it.


 compile 'com.android.support:recyclerview-v7:22.2.1' 


Let's add a toolbar to our activity.


<android.support.v7.widget.Toolbar  
     android:id="@+id/appBar"  
     android:layout_width="match_parent"  
     android:layout_height="@dimen/abc_action_bar_default_height_material"  
     android:background="#00bbff"/> 


We are using Toolbar which is a part of support library v7. We will be using this as our actionbar. For this we need to disable existing actionbar from our theme. Let's do it by using NoActionbar theme. And yes, don't forget to remove the paddings from outermost layout.



<resources>  
   <!-- Base application theme. -->  
   <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  
     <!-- Customize your theme here. -->  
   </style>  
 </resources> 


Then, set the toolbar as actionbar in our activity. Create new field mToolbar for the toolbar and in onCreate assign it the Toolbar  that we created in  using findViewById() method.



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

And let's add DrawerLayout to our layout just below the Toolbar.


 <android.support.v4.widget.DrawerLayout  
     android:id="@+id/drawerLayout"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"
     android:layout_below="@+id/appBar">  
     <!--Content-->  
     <LinearLayout  
       android:layout_width="match_parent"  
       android:layout_height="match_parent"  
       android:orientation="vertical">  
       <TextView  
         android:id="@+id/textView"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_gravity="center"  
         android:text="@string/app_name" />  
     </LinearLayout>  
     <!-- Navigation Drawer-->  
     <android.support.v7.widget.RecyclerView  
       android:id="@+id/drawerRecyclerView"  
       android:layout_width="300dp"  
       android:layout_height="match_parent"  
       android:layout_gravity="left"  
       android:background="#ffffff">  
     </android.support.v7.widget.RecyclerView>  
   </android.support.v4.widget.DrawerLayout> 


In the code above, we used a LinearLayout for the content  and placed a TextView as a page content for now. Then  added Recyclerview for our Navigation Drawer. Now lets set up our recyclerview.


If you notice, Recycler view has an attribute layout_gravity="left" in our code above. Doing this will setup the drawer on the left.


Now, it's time to setup the menu in our navigation drawer, for that let's create a model with an icon and menu title.


public class DrawerItem {  
   private int icon;  
   private String title;  
   public int getIcon() {  
     return icon;  
   }  
   public void setIcon(int icon) {  
     this.icon = icon;  
   }  
   public String getTitle() {  
     return title;  
   }  
   public void setTitle(String title) {  
     this.title = title;  
   }  
 }  

Similarly, create a layout for each menu item. Like this model we just created, the item layout will have an ImageView for icon and a TextView for title.


 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="horizontal" android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:padding="16dp"  
   android:background="?attr/selectableItemBackground">  
   <ImageView  
     android:id="@+id/icon"  
     android:layout_width="24dp"  
     android:layout_height="24dp" />  
   <TextView  
     android:id="@+id/title"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_marginLeft="16dp"/>  
 </LinearLayout>





And, add icons to the project, for now let's use mdpi icons only, DOWNLOAD ICONS FROM HERE.


If you remember from our previous tutorial we need following steps for RecyclerView Setup. (Please follow this tutorial for detailed instructions.)

1. Preparing Menu items
2. Setting up adapter for recyclerview.
     - create viewholder
    - implement three methods.
3. Set layout manager and adapter


Now let's write an Adapter for this recyclerView. Following the above 3 steps our adapter class looks like this.


public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.DrawerViewHolder> {  
   private ArrayList<DrawerItem> drawerMenuList;  
   public DrawerAdapter(ArrayList<DrawerItem> drawerMenuList) {  
     this.drawerMenuList = drawerMenuList;  
   }  
   @Override  
   public DrawerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
     View view;  
     view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_item, parent, false);  
     return new DrawerViewHolder(view);  
   }  
   @Override  
   public void onBindViewHolder(DrawerViewHolder holder, int position) {  
     holder.title.setText(drawerMenuList.get(position).getTitle());  
     holder.icon.setImageResource(drawerMenuList.get(position).getIcon());  
   }  
   @Override  
   public int getItemCount() {  
     return drawerMenuList.size();  
   }  
   class DrawerViewHolder extends RecyclerView.ViewHolder {  
     TextView title;  
     ImageView icon;  
     public DrawerViewHolder(View itemView) {  
       super(itemView);  
       title = (TextView) itemView.findViewById(R.id.title);  
       icon = (ImageView) itemView.findViewById(R.id.icon);  
     }  
   }  
 }  

We will also need the data for our menu, We can use arrays for String and integers and separate them from MainActivity in production code but for now let's just keep it in MainActivity.


//Dummy Data  
     mDrawerItemList = new ArrayList<DrawerItem>();  
     DrawerItem item = new DrawerItem();  
     item.setIcon(R.drawable.inbox);  
     item.setTitle("Inbox");  
     mDrawerItemList.add(item);  
     DrawerItem item2 = new DrawerItem();  
     item2.setIcon(R.drawable.send);  
     item2.setTitle("Send");  
     mDrawerItemList.add(item2);  

Setup RecyclerView with LayoutManager and Adapter in MainActivity.


 DrawerAdapter adapter = new DrawerAdapter(mDrawerItemList);  
     mRecyclerView.setLayoutManager(new LinearLayoutManager(this));  
     mRecyclerView.setAdapter(adapter);  

Now run the app. Navigation drawer can now be opened by dragging from left edge of the screen.




But this is not what we want. We want a toggle for navigation drawer using home icon. For this let's use ActionbarDrawerToggle from support v7 library.


mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close) {  
       @Override  
       public void onDrawerClosed(View drawerView) {  
         super.onDrawerClosed(drawerView);  
         //TODO Add some action here  
         //Executed when drawer closes  
         Toast.makeText(MainActivity.this, "Closed", Toast.LENGTH_SHORT).show();  
       }  
       @Override  
       public void onDrawerOpened(View drawerView) {  
         super.onDrawerOpened(drawerView);  
         //TODO Add some action here  
         //executes when drawer open  
         Toast.makeText(MainActivity.this, "Opened", Toast.LENGTH_SHORT).show();  
       }  
     };  
     mDrawerLayout.setDrawerListener(mDrawerToggle);  
     mDrawerToggle.syncState();  



Let's run the app again. Now we can toggle drawer with  nice animation on home icon.
Now we have a drawer but we haven't yet added header to the drawer. And when we click the menu items, nothing happens yet.

Let's Continue to Part -2 of the tutorial for Adding Header and setting up Click events to menu items.





Tuesday, July 14, 2015

Introduction to RecyclerView

We displayed a vertically scrolling list of items in our previous tutorial using ListView. In this tutorial we will have a look at RecyclerView, one of the very important design elements that help us build apps with material design easily. RecyclerView is included in Android Support Library, So before we proceed make sure you have already downloaded the support Libraries in the SDK Manager.





Click SDK Manager icon from Android Studio to open the SDK Manager, and check if Android Support Repository and Android Support Library are installed.





Once you have installed Support Library you are ready to proceed.


 While using ListView we made use of ViewHolder pattern to increase the ListView performance. We used a ViewHolder class to hold all our views in the list item to avoid looking them up each time the item is displayed. RecyclerView uses the Viewholder pattern by default. In fact we are forced to use the RecyclerView.ViewHolder class while using RecyclerView, that makes us build the lists with better performance.

RecyclerView unlike the ListView is a ViewGroup and it uses LayoutManager to arrange the items.
RecyclerView has three types of LayoutManagers by default that we can use to design our layouts.

1) LinearLayout manager : LinearLayoutManager arranges the items in a linear fashion by arranging the item either in horizontal or vertical orientation.

2) GridLayoutManager : GridLayoutManager is used to arrange the items in a two-dimensional grid arranging the items in rows and columns. GridLayoutManager is used for items with uniform height. If we have items with different heights then all the items will have the same height as the item with maximum height.

3) StaggeredGridLayoutManager: StaggeredGridLayoutManager also arranges items as a grid but is used when we want to have items with different heights.


We will be building the list of the android versions in this tutorial so we will use LinearLayoutManager.

So let's start working with RecyclerView by creating new Android Project.

Since RecyclerView is a part of Support Library we need to declare the dependency in our build.gradle file. Open build.gradle (the one in app module) and then add following dependency.

   compile 'com.android.support:recyclerview-v7:22.2.0'  


Now lets add a RcyclerView to our layout. Open layout/activity_main.xml file and add the RecycleView.

 <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: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.v7.widget.RecyclerView  
     android:id="@+id/recyclerView"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent" />  
 </RelativeLayout>  


Let's define our Model for the list item, Let's create a Java class named AndroidVersion.

 package com.technoguff.recyclerviewexample;  
   

 public class AndroidVersion {  
     
   private String codeName;  
   private String version;  
   private int icon;  
   
   
   public String getCodeName() {  
     return codeName;  
   }  
   
   public void setCodeName(String codeName) {  
     this.codeName = codeName;  
   }  
   
   public String getVersion() {  
     return version;  
   }  
   
   public void setVersion(String version) {  
     this.version = version;  
   }  
   
   public int getIcon() {  
     return icon;  
   }  
   
   public void setIcon(int icon) {  
     this.icon = icon;  
   }  
 }  
   


Then , create a layout for the item view. Create new layout file named layout_item.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">  
   <ImageView  
     android:id="@+id/ivIcon"  
     android:layout_width="64dp"  
     android:layout_height="64dp"   
     android:layout_margin="5dp"/>  
   
   <TextView  
     android:id="@+id/codeName"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_toRightOf="@+id/ivIcon"  
     android:textStyle="bold"  
     android:textSize="20sp"  
     />  
   
   <TextView  
     android:id="@+id/version"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_toRightOf="@id/ivIcon"  
     android:layout_below="@+id/codeName"  
     />  
   
 </RelativeLayout>  


Now, Create some sample data for our listview by creating an ArrayList of AndroidVersions in MainActivity and create drawable-mdpi folder in res folder of our project. And then place the icons for different versions. GET THE ICONS HERE.

 public class MainActivity extends AppCompatActivity {  
   private ArrayList<AndroidVersion> mVersionList;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     //Sample Data :: For this tutorial, let's just create sample data in the main activity. In real projects  
     // we will either get the data for our list item from webservices or local storage.  
     mVersionList = new ArrayList<AndroidVersion>();  
     AndroidVersion version = new AndroidVersion();  
     version = new AndroidVersion();  
     version.setCodeName("Cupcake");  
     version.setVersion("Android 1.5");  
     version.setIcon(R.drawable.cupcake);  
     mVersionList.add(version);  
     version = new AndroidVersion();  
     version.setCodeName("Donut");  
     version.setVersion("Android 1.6");  
     version.setIcon(R.drawable.donut);  
     mVersionList.add(version);  
     version = new AndroidVersion();  
     version.setCodeName("Eclair");  
     version.setVersion("Android 2.0");  
     version.setIcon(R.drawable.eclair);  
     mVersionList.add(version);  
     version = new AndroidVersion();  
     version.setCodeName("Froyo");  
     version.setVersion("Android 2.2");  
     version.setIcon(R.drawable.froyo);  
     mVersionList.add(version);  
     version = new AndroidVersion();  
     version.setCodeName("Gingerbread");  
     version.setVersion("Android 2.3");  
     version.setIcon(R.drawable.gingerbread);  
     mVersionList.add(version);  
 ....  
 ....  
 ....  
 ..  


Now we have created the sample data for the list we will now populate it to our RecyclerView. For that let's create an Adapter. RecyclerView provides RecyclerView.Adapter class for creating the adapter. Let's add the adapter.


Create a Java class and extend it from RecyclerView.Adapter, we will have  define the ViewHolder for the Adapter so create a View holder. Let's name it MyViewHolder.

Create the required constructor and add the override methods required by the Adapter class.

Now our Adapter looks like this,



 public class AndroidVersionAdapter extends RecyclerView.Adapter<AndroidVersionAdapter.MyViewHolder>{  
   @Override  
   public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {  
     return null;  
   }  
   @Override  
   public void onBindViewHolder(MyViewHolder myViewHolder, int i) {  
   }  
   @Override  
   public int getItemCount() {  
     return 0;  
   }  
   class MyViewHolder extends RecyclerView.ViewHolder{  
     public MyViewHolder(View itemView) {  
       super(itemView);  
     }  
   }  
 }  


Next, we will need the data for the Adapter let's add a constructor to AndroidVersionAdapter.

 ArrayList<AndroidVersion> mVersionList;  
   public AndroidVersionAdapter(ArrayList<AndroidVersion> versionList) {  
     mVersionList = versionList;  
   }  


Now update MyViewHolder class so that it finds the views in our itemLayout.

 //ViewHolder  
   class MyViewHolder extends RecyclerView.ViewHolder{  
     TextView codeName;  
     TextView version;  
     ImageView iconImage;  
     public MyViewHolder(View itemView) {  
       super(itemView);  
       codeName = (TextView)itemView.findViewById(R.id.codeName);  
       version = (TextView)itemView.findViewById(R.id.version);  
       iconImage = (ImageView) itemView.findViewById(R.id.ivIcon);  
     }  
   }  

Now let's have a look at the three methods that we override.

1) onCreateViewHolder

      onCreateViewHolder is called by the Layout manager when ViewHolder is created to inflate the layout we defined in XML, and ViewHolder finds each view in the given Layout.

2) onBindViewHolder

     onBindViewHolder  is also called by the LayoutManager to populate the data to the views.

3) getItemCount

     This method is used by LayoutManager to know the size of our Data.

Let's implement these three methods.


   @Override  
   public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {  
     LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());  
     View view = inflater.inflate(R.layout.layout_item, viewGroup, false);  
     MyViewHolder holder = new MyViewHolder(view);  
     return holder;  
   }  
   @Override  
   public void onBindViewHolder(MyViewHolder myViewHolder, int i) {  
     AndroidVersion version = mVersionList.get(i);  
     myViewHolder.codeName.setText(version.getCodeName());  
     myViewHolder.version.setText(version.getVersion());  
     myViewHolder.iconImage.setImageResource(version.getIcon());  
   }  
   @Override  
   public int getItemCount() {  
     return mVersionList.size();  
   }  



Next step is to set this adapter to the RecyclerView.

  private RecyclerView mRecyclerView;  
   private AndroidVersionAdapter mAdapter;  

and in onCreate,

 LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);  
     mRecyclerView.setLayoutManager(mLayoutManager);  
     mRecyclerView.setAdapter(mAdapter);  


We used LinearLayoutManager to arrange our items, Let't run the app and see how it looks.






Now let's change it to GridLayoutManager with span value of 2 which makes the view arrange in two columns.

 GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2);