Google’s upcoming operating system named Android L looks very promising. It is highly focused on rich user experience and what they called it as material design. In this example we will take a look at the new UI widget called RecyclerView
.
RecyclerView
is more advanced and flexible and efficient version of ListView. RecyclerView ViewGroup is an container for larger data set of views that can be recycled and scrolled very efficiently. RecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design different kind of views.
Just like ListView, RecyclerView is used to display a large amount of similar items on screen. But since the Android team was building an enhancement, they added a bunch of new features to RecyclerView. Each one of these new features, give a platform to developers for implementing a highly custom made RecyclerView. One of the custom implementations of RecyclerView is the new Gmail app on Android.
In this tutorial, we are going to learn how to use RecyclerView to show items in List RecyclerView and Grid RecyclerView.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Android SDK doesn’t includes the RecyclerView
class, and hence for using RecyclerView in your project you first need to add the recycler view support library to your project. You can download recyclerview library from here.
3. Firstly create a layout naming recycler_view.xml for using this layout in this tutorial as we had done in Toolbar tutorial.
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8"?> <!-- Recycler view --> <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:overScrollMode="never" android:scrollbars="none" /> |
4. As you had seen in above video i am using tabs for displaying list and grid items. So i am using viewpager for this in activity_main.xml. If you are not aware of the ViewPager then you can refer to my ViewPager tutorial.
1 2 3 4 5 6 |
<!-- ViewPager for tabs --> <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" /> |
5. Now, we need to create two more layout for List and Grid items. This layouts will be used in fragments for tabs. If you are not aware of fragments then you can refer to Fragments tutorial.
In both layouts i am including recyclerview layout that i had created above. You can use single layout for both fragments.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- include recyclerview layout --> <include android:id="@+id/linear_recyclerview" layout="@layout/recycler_view" /> </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- include recyclerview layout --> <include android:id="@+id/grid_recyclerview" layout="@layout/recycler_view" /> </LinearLayout> |
6. Now, we have to create another two more layouts for both List and Grid custom layouts. This layouts are going to be used in recyclerview adapter for inflating over recycler view.
Since, both List and Grid are different in layout so they will need different custom layout.
List Custom View xml Layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ffffff" android:padding="10dp" > <ImageView android:id="@+id/list_imageview" android:layout_width="100dp" android:layout_height="120dp" android:adjustViewBounds="true" android:contentDescription="@string/imageview" android:scaleType="centerCrop" /> <ImageView android:id="@+id/list_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/list_item_holder" android:contentDescription="@string/delete_image" android:src="@drawable/ic_delete" /> <LinearLayout android:id="@+id/list_item_holder" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/list_imageview" android:orientation="vertical" > <TextView android:id="@+id/list_title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="3dp" android:paddingLeft="10dp" android:textColor="#000000" android:textSize="17sp" /> <TextView android:id="@+id/list_location" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="3dp" android:paddingLeft="10dp" android:textColor="#757575" android:textSize="14sp" /> <TextView android:id="@+id/list_dateconstructed" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dp" android:textColor="#757575" android:textSize="14sp" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> |
Grid Custom View xml Layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ffffff" android:padding="10dp" > <ImageView android:id="@+id/grid_imageview" android:layout_width="100dp" android:layout_height="120dp" android:layout_gravity="center" android:adjustViewBounds="true" android:layout_centerHorizontal="true" android:contentDescription="@string/imageview" android:scaleType="centerCrop" /> <TextView android:id="@+id/grid_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/grid_imageview" android:gravity="center" android:paddingBottom="3dp" android:paddingLeft="10dp" android:layout_centerHorizontal="true" android:singleLine="true" android:textColor="#000000" android:textSize="15sp" /> <ImageView android:id="@+id/grid_delete" android:layout_width="20dp" android:layout_height="20dp" android:layout_alignRight="@+id/grid_imageview" android:layout_alignTop="@+id/grid_imageview" android:layout_marginLeft="5dp" android:contentDescription="@string/delete_image" android:src="@drawable/ic_delete" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/grid_title" android:gravity="center_horizontal" android:orientation="horizontal" > <TextView android:id="@+id/grid_location" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="start" android:paddingBottom="3dp" android:paddingLeft="5dp" android:textColor="#757575" android:textSize="14sp" /> <TextView android:id="@+id/grid_dateconstructed" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="end" android:paddingLeft="5dp" android:paddingRight="5dp" android:textColor="#757575" android:textSize="14sp" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> |
7. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial and there are String Array also that is for items data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">RecyclerView Demo</string> <string name="hello_world">Hello world!</string> <string name="add">Add</string> <string name="remove">Remove</string> <string name="imageview">ImageView</string> <string name="delete_image">Delete ImageView</string> <!-- Title string array --> <string-array name="title"> <item>Taj Mahal</item> <item>Hawa Mahal</item> <item>Golden Temple</item> <item>Shore Temple</item> <item>Chhatrapati Shivaji Terminus</item> <item>Lotus Temple</item> <item>Victoria Memorial Hall</item> <item>Brihadeeswarar Temple</item> <item>Mahabodhi Temple</item> </string-array> <!-- Location string array --> <string-array name="location"> <item>Agra</item> <item>Jaipur</item> <item>Amritsar</item> <item>Bay of Bengal</item> <item>Mumbai</item> <item>New Delhi</item> <item>Kolkata</item> <item>Tamil Nadu</item> <item>Patna</item> </string-array> <!-- Year string array --> <string-array name="constructed_year"> <item>1632</item> <item>1799 AD</item> <item>1577</item> <item>700–728 AD</item> <item>May 1888</item> <item>1987</item> <item>1906</item> <item>1010 CE</item> <item>250 BCE</item> </string-array> </resources> |
8. Before moving further, we have to create a ViewHolder for both List and Grid recyclerview. For this we have to two new java classes. In this classes we have to extend the class with RecyclerView.ViewHolder. In this classes i had used click listener for implementing click listener over recycler view items. We have to setClickListener for all views which we want to do something on click.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.erecyclerview_demo.holders; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.erecyclerview_demo.R; public class ListView_Holder extends RecyclerView.ViewHolder implements OnClickListener { // View holder for list recycler view as we used in listview public TextView list_title, list_location, list_date; public ImageView list_imageView, list_delete; public RelativeLayout listLayout; private RecyclerView_OnClickListener.OnClickListener onClickListener; public ListView_Holder(View view) { super(view); // Find all views ids this.list_title = (TextView) view.findViewById(R.id.list_title); this.list_location = (TextView) view.findViewById(R.id.list_location); this.list_date = (TextView) view .findViewById(R.id.list_dateconstructed); this.list_imageView = (ImageView) view .findViewById(R.id.list_imageview); this.list_delete = (ImageView) view.findViewById(R.id.list_delete); this.listLayout = (RelativeLayout) view.findViewById(R.id.list_layout); // Implement click listener over views that we need this.list_delete.setOnClickListener(this); this.listLayout.setOnClickListener(this); } @Override public void onClick(View v) { // setting custom listener if (onClickListener != null) { onClickListener.OnItemClick(v, getAdapterPosition()); } } // Setter for listener public void setClickListener( RecyclerView_OnClickListener.OnClickListener onClickListener) { this.onClickListener = onClickListener; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.erecyclerview_demo.holders; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.erecyclerview_demo.R; public class GridView_Holder extends RecyclerView.ViewHolder implements OnClickListener { // View holder for gridview recycler view as we used in listview public TextView grid_title, grid_location, grid_date; public ImageView grid_imageView, grid_delete; public RelativeLayout gridLayout; private RecyclerView_OnClickListener.OnClickListener onClickListener; public GridView_Holder(View view) { super(view); // Find all views ids this.grid_title = (TextView) view.findViewById(R.id.grid_title); this.grid_location = (TextView) view.findViewById(R.id.grid_location); this.grid_date = (TextView) view .findViewById(R.id.grid_dateconstructed); this.grid_imageView = (ImageView) view .findViewById(R.id.grid_imageview); this.grid_delete = (ImageView) view.findViewById(R.id.grid_delete); this.gridLayout = (RelativeLayout) view.findViewById(R.id.grid_layout); // Implement click listener over views that we want this.gridLayout.setOnClickListener(this); this.grid_delete.setOnClickListener(this); } @Override public void onClick(View v) { // set custom listener if (onClickListener != null) { onClickListener.OnItemClick(v, getAdapterPosition()); } } // Setter for listener public void setClickListener( RecyclerView_OnClickListener.OnClickListener onClickListener) { this.onClickListener = onClickListener; } } |
9. Now, create a getter and setter class for recyclerView. As we use to create in ListView and GridView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.erecyclerview_demo; public class Data_Model { // Getter and Setter model for recycler view items private String title, location, year; private int image; public Data_Model(String title, String location, String year, int image) { this.year = year; this.title = title; this.location = location; this.image = image; } public String getTitle() { return title; } public String getLocation() { return location; } public String getYear() { return year; } public int getImage() { return image; } } |
10. Android RecyclerView included special kind of adapter which works pretty much same as traditional Android adapters but with additional functionalities. The additional functionalities inclued :
onCreateViewHolder()
and onBindViewHolder()
to organize the code. You must override these two methods for inflate the view and to bind data to the viewRecyclerView.ViewHolder
works same as the ViewHolder design pattern which we have been using with other Adapters.This is onCreateViewHolder method for List RecyclerView
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public ListView_Holder onCreateViewHolder(ViewGroup viewGroup, int viewType) { // This method will inflate the custom layout and return as viewholder LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.list_customview, viewGroup, false); ListView_Holder listHolder = new ListView_Holder(mainGroup); return listHolder; } |
This is onBindViewHolde method for List RecyclerView in this method we have to set items over views.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Override public void onBindViewHolder(ListView_Holder holder, int position) { final Data_Model model = arrayList.get(position); ListView_Holder mainHolder = (ListView_Holder) holder;// holder Bitmap image = BitmapFactory.decodeResource(context.getResources(), model.getImage());// This will convert drawbale image into // bitmap // setting data over views mainHolder.list_title.setText(model.getTitle()); mainHolder.list_location.setText(model.getLocation()); mainHolder.list_date.setText(model.getYear()); mainHolder.list_imageView.setImageBitmap(image); } |
ListRecycelrView Adapter Class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
package com.erecyclerview_demo.adapter; import java.util.ArrayList; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.erecyclerview_demo.Data_Model; import com.erecyclerview_demo.R; import com.erecyclerview_demo.holders.ListView_Holder; import com.erecyclerview_demo.holders.RecyclerView_OnClickListener.OnClickListener; public class ListView_Recycler_Adapter extends RecyclerView.Adapter<ListView_Holder> {// Recyclerview will extend to // recyclerview adapter private ArrayList<Data_Model> arrayList; private Context context; public ListView_Recycler_Adapter(Context context, ArrayList<Data_Model> arrayList) { this.context = context; this.arrayList = arrayList; } @Override public int getItemCount() { return (null != arrayList ? arrayList.size() : 0); } @Override public void onBindViewHolder(ListView_Holder holder, int position) { final Data_Model model = arrayList.get(position); ListView_Holder mainHolder = (ListView_Holder) holder;// holder Bitmap image = BitmapFactory.decodeResource(context.getResources(), model.getImage());// This will convert drawbale image into // bitmap // setting data over views mainHolder.list_title.setText(model.getTitle()); mainHolder.list_location.setText(model.getLocation()); mainHolder.list_date.setText(model.getYear()); mainHolder.list_imageView.setImageBitmap(image); // Implement click listener over layout mainHolder.setClickListener(new OnClickListener() { @Override public void OnItemClick(View view, int position) { switch (view.getId()) { case R.id.list_layout: // Show a toast on clicking layout Toast.makeText(context, "You have clicked " + model.getTitle(), Toast.LENGTH_LONG).show(); break; case R.id.list_delete: // remove selected item arrayList.remove(position); notifyItemRemoved(position); break; } } }); } @Override public ListView_Holder onCreateViewHolder(ViewGroup viewGroup, int viewType) { // This method will inflate the custom layout and return as viewholder LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.list_customview, viewGroup, false); ListView_Holder listHolder = new ListView_Holder(mainGroup); return listHolder; } } |
GridRecyclerView Adapter Class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
package com.erecyclerview_demo.adapter; import java.util.ArrayList; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.erecyclerview_demo.Data_Model; import com.erecyclerview_demo.R; import com.erecyclerview_demo.holders.GridView_Holder; import com.erecyclerview_demo.holders.RecyclerView_OnClickListener.OnClickListener; public class GridView_Recycler_Adapter extends RecyclerView.Adapter<GridView_Holder> { // Recyclerview will always // extend to recyclerview // adapter private ArrayList<Data_Model> arrayList; private Context context; public GridView_Recycler_Adapter(Context context, ArrayList<Data_Model> arrayList) { this.context = context; this.arrayList = arrayList; } @Override public int getItemCount() { return (null != arrayList ? arrayList.size() : 0); } @Override public void onBindViewHolder(GridView_Holder holder, int position) { // Now in this method the items will set and click listener will occur final Data_Model model = arrayList.get(position); GridView_Holder gridHolder = (GridView_Holder) holder;// Holder Bitmap image = BitmapFactory.decodeResource(context.getResources(), model.getImage());// Converting drawable into bitmap // setting data over views gridHolder.grid_title.setText(model.getTitle()); gridHolder.grid_location.setText(model.getLocation()); gridHolder.grid_date.setText(model.getYear()); gridHolder.grid_imageView.setImageBitmap(image); // Implementing click listener gridHolder.setClickListener(new OnClickListener() { @Override public void OnItemClick(View view, int position) { switch (view.getId()) { case R.id.grid_layout: // Toast will shown when layout is clicked Toast.makeText(context, "You have clicked " + model.getTitle(), Toast.LENGTH_LONG).show(); break; case R.id.grid_delete: // Item will deleted when delete image clicked arrayList.remove(position); notifyItemRemoved(position);// Notify adapter of removed // position break; } } }); } @Override public GridView_Holder onCreateViewHolder(ViewGroup viewGroup, int viewType) { // This method will inflate the layout and return as viewholder LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.grid_customview, viewGroup, false); GridView_Holder gridHolder = new GridView_Holder(mainGroup); return gridHolder; } } |
12. Handling click event on RecyclerView is not as sweet as handling click listener in ListView or GridView. Android RecyclerView doesn’t provide any built in listeners or handy way of handling click events.
For this I created an interface class for onClickListener you can implement this interface in all ViewHolder and implement clickListener.
1 2 3 4 5 6 7 8 9 10 |
package com.erecyclerview_demo.holders; import android.view.View; public class RecyclerView_OnClickListener { /** Interface for Item Click over Recycler View Items **/ public interface OnClickListener { public void OnItemClick(View view, int position); } } |
Now we can use this interface to handle click event explicitly by adding the following code in onBindViewHolder()
method. As we had done in above adapter classes.
13. RecyclerView having two LayoutManagers for showing data. LinearLayoutManager for List items and GridLayoutManager for Grid items. The below code is for List items using LinearLayoutManager and LayoutManager is neccessary in RecyclerView.
1 2 3 4 5 |
listRecyclerView = (RecyclerView) view .findViewById(R.id.linear_recyclerview); listRecyclerView.setHasFixedSize(true); listRecyclerView .setLayoutManager(new LinearLayoutManager(getActivity()));/ |
Full Code of List RecyclerView fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
package com.erecyclerview_demo; import java.util.ArrayList; import java.util.Random; import android.os.Bundle; 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.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import com.erecyclerview_demo.adapter.ListView_Recycler_Adapter; public class LinearLayout_Fragment extends Fragment { private static View view; private static RecyclerView listRecyclerView; private static ArrayList<Data_Model> listArrayList; private static ListView_Recycler_Adapter adapter; // Images array for images private static final int[] images = { R.drawable.tajmahal, R.drawable.hawamahal, R.drawable.golden, R.drawable.shore, R.drawable.shivaji, R.drawable.lotus, R.drawable.victoria, R.drawable.brihadishwara, R.drawable.mahabodhi }; // String array for title, location, year String[] getTitle, getLocation, getYear; public LinearLayout_Fragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.linearlayout_fragment, container, false); init(); populatRecyclerView(); setHasOptionsMenu(true);// this method used to set option menu on // fragment return view; } // Initialize the view private void init() { // Getting the string array from strings.xml getTitle = getActivity().getResources().getStringArray(R.array.title); getLocation = getActivity().getResources().getStringArray( R.array.location); getYear = getActivity().getResources().getStringArray( R.array.constructed_year); listArrayList = new ArrayList<Data_Model>(); listRecyclerView = (RecyclerView) view .findViewById(R.id.linear_recyclerview); listRecyclerView.setHasFixedSize(true); listRecyclerView .setLayoutManager(new LinearLayoutManager(getActivity()));// for // linear // data // display // we // use // linear // layoutmanager } // populate the list view by adding data to arraylist private void populatRecyclerView() { for (int i = 0; i < getTitle.length; i++) { listArrayList.add(new Data_Model(getTitle[i], getLocation[i], getYear[i], images[i])); } adapter = new ListView_Recycler_Adapter(getActivity(), listArrayList); listRecyclerView.setAdapter(adapter);// set adapter on recyclerview adapter.notifyDataSetChanged();// Notify the adapter } // random generator method for generating data in int nos. private int RandomGenerator() { Random random = new Random(); int randomNum = random.nextInt(9); return randomNum; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.main, menu); MenuItem add = menu.findItem(R.id.add); add.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem arg0) { int value = RandomGenerator();// get random value from random // method // add random data to arraylist listArrayList.add(new Data_Model(getTitle[value], getLocation[value], getYear[value], images[value])); adapter.notifyDataSetChanged();// finally notify adapter return false; } }); super.onCreateOptionsMenu(menu, inflater); } } |
Full Code of Grid RecyclerView fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
package com.erecyclerview_demo; import java.util.ArrayList; import java.util.Random; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import com.erecyclerview_demo.adapter.GridView_Recycler_Adapter; public class GridLayout_Fragment extends Fragment { private static View view; private static RecyclerView gridRecyclerView; private static GridView_Recycler_Adapter adapter; private static ArrayList<Data_Model> gridArrayList; // Images int array from drawable folders private static final int[] images = { R.drawable.tajmahal, R.drawable.hawamahal, R.drawable.golden, R.drawable.shore, R.drawable.shivaji, R.drawable.lotus, R.drawable.victoria, R.drawable.brihadishwara, R.drawable.mahabodhi }; // String array for title, location,year String[] getTitle, getLocation, getYear; public GridLayout_Fragment() { // Empty constructor is neccessary } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.gridlayout_fragment, container, false); init(); populatRecyclerView(); setHasOptionsMenu(true);// This will set option menu on fragment return view; } // Initialize all variables and views private void init() { // Get the title , location and year from string.xml in array form getTitle = getActivity().getResources().getStringArray(R.array.title); getLocation = getActivity().getResources().getStringArray( R.array.location); getYear = getActivity().getResources().getStringArray( R.array.constructed_year); gridArrayList = new ArrayList<Data_Model>(); // Find the id of recycler view gridRecyclerView = (RecyclerView) view .findViewById(R.id.grid_recyclerview); gridRecyclerView.setHasFixedSize(true);// set it fixed size // Set layout manager, we need grid layout manager here for gridview gridRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));// "2" denotes the no. of spancount i.e. no. of items in a // row and setting layout manager is neccessary } // Populate the listview with data private void populatRecyclerView() { for (int i = 0; i < getTitle.length; i++) { // add the items one by one in arraylist gridArrayList.add(new Data_Model(getTitle[i], getLocation[i], getYear[i], images[i])); } adapter = new GridView_Recycler_Adapter(getActivity(), gridArrayList); // set adapter over recyclerview gridRecyclerView.setAdapter(adapter); adapter.notifyDataSetChanged(); } // Random generator method this will generate int nos. private int RandomGenerator() { Random random = new Random(); int randomNum = random.nextInt(9); return randomNum; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.main, menu);// Inflate // option // menu // Find the id of menu MenuItem add = menu.findItem(R.id.add); // Implement click listener on menu item add.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem arg0) { int value = RandomGenerator();// Get int value from random // generaor method // Now add the data to arraylist by random value gridArrayList.add(new Data_Model(getTitle[value], getLocation[value], getYear[value], images[value])); adapter.notifyDataSetChanged();// finally notify adapter return false; } }); super.onCreateOptionsMenu(menu, inflater); } } |
In above both fragment classes i am adding items dynamically by using a RandomGenerator method.
14. Finally, come to MainActivity.java and add the following code to set tab fragment over ViewPager.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
package com.erecyclerview_demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.Tab; import android.support.v7.app.ActionBar.TabListener; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements TabListener { private static ViewPager viewPager;//View Pager for setting tabs private static ActionBar actionBar; private static FragmentManager fragmentManager;//fragment manager to work on fragments @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setTabs(); } //initialize the view pager private void init() { viewPager = (ViewPager) findViewById(R.id.pager); fragmentManager = getSupportFragmentManager(); // Setting adapter over view pager viewPager.setAdapter(new MyAdapter(fragmentManager)); // Implementing view pager pagechangelistener to navigate between tabs viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int pos) { // Setting navigation of tabs to actionbar actionBar.setSelectedNavigationItem(pos); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } private void setTabs() { // Getting actionbar actionBar = getSupportActionBar(); // Setting navigation mode to actionbar actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Now adding a new tab to action bar and setting title, icon and // implementing listener android.support.v7.app.ActionBar.Tab tab1 = actionBar.newTab(); tab1.setText("ListView"); // tab1.setIcon(R.drawable.ic_launcher); tab1.setTabListener(this); android.support.v7.app.ActionBar.Tab tab2 = actionBar.newTab(); tab2.setText("GridView"); tab2.setTabListener(this); // Now finally adding all tabs to actionbar actionBar.addTab(tab1); actionBar.addTab(tab2); } @Override public void onTabReselected(Tab arg0, FragmentTransaction arg1) { } @Override public void onTabSelected(Tab tab, FragmentTransaction arg1) { // Setting current position of tab to view pager viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab arg0, FragmentTransaction arg1) { } // My adapter i.e. custom adapter for displaying fragments over view pager private class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { // Getting fragments according to selected position Fragment fragment = null; if (i == 0) { fragment = new LinearLayout_Fragment(); } if (i == 1) { fragment = new GridLayout_Fragment(); } // and finally returning fragments return fragment; } @Override public int getCount() { // Returning no. of counts of fragments return 2; } } } |
15. Now, you are all done, run your app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.
2 Comments
Mario German
Tuesday, August 9th, 2016Thanks for sharing your knowledge with everyone, I wanted to ask how I can place a spinner in a recyclcerview, you have some tutorial or link about this, you appreciate too.
Dr. Droid
Friday, August 12th, 2016Hi Mario,
Sorry for late!! Check this link to implement Spinner in Recycler View : http://www.codeproject.com/Articles/1033283/Android-Recycler-View-with-Spinner-Item-Change-Sel
Thanks