Combining Navigation Drawer and Recycler View in ViewPager Fragments( with tabs)

In android development, Navigation Drawer and Recycler View and tabs layout are some of the most popular interfaces that are used in apps. We often think to collaborate different types of layout in a single screen., with DrawerLayout, NavigationView, ViewPager, RecyclerView, CardView and TabLayout. With material design style, the theme can be combined in an Activity.


Firstly, add the design support library dependency to use Material Design Widgets, add RecyclerView dependency and CardView dependency to use them:

app/build.gradle
  1. apply plugin: 'com.android.application'

  2. android {
  3.     compileSdkVersion 24
  4.     buildToolsVersion "25.0.0"
  5.     defaultConfig {
  6.         applicationId "test.ku.codedivas.sampleapp"
  7.         minSdkVersion 14
  8.         targetSdkVersion 24
  9.         versionCode 1
  10.         versionName "1.0"
  11.         
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  13.     }
  14.     buildTypes {
  15.         release {
  16.             minifyEnabled false
  17.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  18.         }
  19.     }
  20. }

  21. dependencies {
  22.     compile fileTree(dir: 'libs', include: ['*.jar'])
  23.     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  24.         exclude group: 'com.android.support', module: 'support-annotations'
  25.     })
  26.     compile 'com.android.support:appcompat-v7:24.2.1'
  27.     compile 'com.android.support:design:24.2.1'
  28.     compile 'com.android.support:recyclerview-v7:24.2.0'
  29.     compile 'com.android.support:cardview-v7:24.2.0'
  30.     testCompile 'junit:junit:4.12'

  31. }

Designing Activity Layout


The layout should be like:

activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     xmlns:app="http://schemas.android.com/apk/res-auto">

  7.     <android.support.v7.widget.Toolbar
  8.         android:id="@+id/toolbar"
  9.         android:layout_width="match_parent"
  10.         android:layout_height="?attr/actionBarSize"
  11.         android:background="?attr/colorPrimary"
  12.         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

  13.     <android.support.v4.widget.DrawerLayout
  14.         android:id="@+id/drawerLayout"
  15.         android:layout_width="match_parent"
  16.         android:layout_height="match_parent"
  17.         android:fitsSystemWindows="true"
  18.         xmlns:tools="http://schemas.android.com/tools"
  19.         tools:openDrawer="start">

  20.         <LinearLayout android:layout_width="match_parent"
  21.             android:layout_height="match_parent"
  22.             xmlns:app="http://schemas.android.com/apk/res-auto"
  23.             android:orientation="vertical"
  24.             xmlns:android="http://schemas.android.com/apk/res/android">

  25.             <android.support.design.widget.TabLayout
  26.                 android:id="@+id/tab_layout"
  27.                 android:layout_width="match_parent"
  28.                 app:tabGravity="fill"
  29.                 app:tabMode="fixed"
  30.                 android:layout_height="?attr/actionBarSize"
  31.                 android:background="@color/colorPrimary"
  32.                 android:minHeight="?attr/actionBarSize"
  33.                 android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

  34.             <android.support.v4.view.ViewPager
  35.                 android:id="@+id/view_pager"
  36.                 android:layout_width="match_parent"
  37.                 android:layout_height="wrap_content" />
  38.         </LinearLayout>

  39.         <android.support.design.widget.NavigationView
  40.             android:id="@+id/nav_view"
  41.             android:layout_width="wrap_content"
  42.             android:layout_height="match_parent"
  43.             android:layout_gravity="start"
  44.             android:fitsSystemWindows="true"
  45.             app:headerLayout="@layout/nav_header_main"
  46.             app:menu="@menu/activity_main_drawer" />

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

  48. </LinearLayout>
Here, We have to put ViewPager and Tab Layout in the first child of DrawerLayout, it will make a swipeable view with tabs later and it's child is a Navigation View.

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

  2. <LinearLayout 
  3.     xmlns:android="http://schemas.android.com/apk/res/android"
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="160dp"
  7.     android:paddingBottom="16dp"
  8.     android:paddingLeft="16dp"
  9.     android:paddingRight="16dp"
  10.     android:paddingTop="16dp"
  11.     android:theme="@style/ThemeOverlay.AppCompat.Dark"
  12.     android:orientation="vertical"
  13.     android:gravity="bottom">

  14.     <ImageView
  15.         android:layout_width="wrap_content"
  16.         android:layout_height="wrap_content"
  17.         android:paddingTop="16dp"
  18.         app:srcCompat="@mipmap/ic_launcher"
  19.         android:id="@+id/imageView" />

  20.     <TextView
  21.         android:layout_width="match_parent"
  22.         android:layout_height="wrap_content"
  23.         android:paddingTop="16dp"
  24.         android:text="Android Studio"
  25.         android:textColor="#ffffff"
  26.         android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

  27.     <TextView
  28.         android:layout_width="wrap_content"
  29.         android:layout_height="wrap_content"
  30.         android:text="android.studio@android.com"
  31.         android:textAppearance="?android:textAppearanceSmall"
  32.         android:textColor="#ffffff"
  33.         android:textStyle="bold"
  34.         android:id="@+id/textView" />

  35. </LinearLayout>
The nav_header_main.xml file is made to build the sliding menu drawer.


activity_main_drawer.xml

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

  3.     <group android:checkableBehavior="single">
  4.         <item
  5.             android:id="@+id/nav_camera"
  6.             android:icon="@drawable/ic_menu_camera"
  7.             android:title="Fragment One" />
  8.         <item
  9.             android:id="@+id/nav_gallery"
  10.             android:icon="@drawable/ic_menu_gallery"
  11.             android:title="Fragment Two" />
  12.         <item
  13.             android:id="@+id/nav_slideshow"
  14.             android:icon="@drawable/ic_menu_slideshow"
  15.             android:title="Fragment Three" />
  16.         <item
  17.             android:id="@+id/nav_manage"
  18.             android:icon="@drawable/ic_menu_manage"
  19.             android:title="NextActivity" />
  20.     </group>

  21.     <item android:title="Communicate">
  22.         <menu>
  23.             <item
  24.                 android:id="@+id/nav_share"
  25.                 android:icon="@drawable/ic_menu_share"
  26.                 android:title="Share" />
  27.             <item
  28.                 android:id="@+id/nav_send"
  29.                 android:icon="@drawable/ic_menu_send"
  30.                 android:title="Send" />
  31.         </menu>
  32.     </item>

  33. </menu>
The activity_main_drawer.xml file is made to fill the values into sliding menu drawer.

Program Code

In our Main Activity, make sure to locate all the views, set the adapter for ViewPager (containing fragments which have RecyclerView embedded), attach TabLayout with ViewPager. It must implement OnNavigationItemSelectedListener interface to handle NavigationView item clicked event.

Source code should be like:

MainActivity.java

  1. package test.ku.codedivas.sampleapp;

  2. import android.content.Intent;
  3. import android.os.Bundle;
  4. import android.support.design.widget.FloatingActionButton;
  5. import android.support.design.widget.Snackbar;
  6. import android.support.design.widget.TabLayout;
  7. import android.support.v4.app.FragmentManager;
  8. import android.support.v4.view.ViewPager;
  9. import android.view.View;
  10. import android.support.design.widget.NavigationView;
  11. import android.support.v4.view.GravityCompat;
  12. import android.support.v4.widget.DrawerLayout;
  13. import android.support.v7.app.ActionBarDrawerToggle;
  14. import android.support.v7.app.AppCompatActivity;
  15. import android.support.v7.widget.Toolbar;
  16. import android.view.Menu;
  17. import android.view.MenuItem;

  18. public class MainActivity extends AppCompatActivity
  19.         implements NavigationView.OnNavigationItemSelectedListener {

  20.     private ViewPager viewPager;
  21.     private DrawerLayout drawer;
  22.     public String title;

  23.     private TabLayout tabLayout;
  24.     private String[] pageTitle = {"First", "Second", "Third"};

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

  29.         viewPager = (ViewPager)findViewById(R.id.view_pager);

  30.         tabLayout = (TabLayout) findViewById(R.id.tab_layout);
  31.         for (int i = 0; i < 3; i++) {
  32.             tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
  33.         }

  34.         //set gravity for tab bar
  35.         tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

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

  38.         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
  39.         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
  40.                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  41.         drawer.setDrawerListener(toggle);
  42.         toggle.syncState();

  43.         NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
  44.         assert navigationView != null;
  45.         navigationView.setNavigationItemSelectedListener(this);

  46.         //set viewpager adapter
  47.         ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
  48.         viewPager.setAdapter(pagerAdapter);

  49.         //change Tab selection when swipe ViewPager
  50.     viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

  51.         //change ViewPager page when tab selected
  52.         tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
  53.             @Override
  54.             public void onTabSelected(TabLayout.Tab tab) {
  55.                 viewPager.setCurrentItem(tab.getPosition());
  56.             }

  57.             @Override
  58.             public void onTabUnselected(TabLayout.Tab tab) {
  59.             }

  60.             @Override
  61.             public void onTabReselected(TabLayout.Tab tab) {
  62.             }
  63.         });

  64.         if (savedInstanceState == null) {
  65.             navigationView.getMenu().performIdentifierAction(R.id.nav_camera,0);
  66.         }
  67.     }

  68.     @Override
  69.     public void onBackPressed() {
  70.         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
  71.         if (drawer.isDrawerOpen(GravityCompat.START)) {
  72.             drawer.closeDrawer(GravityCompat.START);
  73.         } else {
  74.             super.onBackPressed();
  75.         }
  76.     }

  77.     @SuppressWarnings("StatementWithEmptyBody")
  78.     @Override
  79.     public boolean onNavigationItemSelected(MenuItem item) {
  80.         // Handle navigation view item clicks here.

  81.         FragmentManager fm  = getSupportFragmentManager();
  82.         switch(item.getItemId()) {
  83.             case R.id.nav_camera:
  84.                 title="Sample App";
  85.                 viewPager.setCurrentItem(0);
  86.                 break;

  87.             case R.id.nav_gallery:
  88.                 viewPager.setCurrentItem(1);
  89.                 break;

  90.             case R.id.nav_slideshow:
  91.                 viewPager.setCurrentItem(2);
  92.                 break;

  93.             case R.id.nav_manage:
  94.                 Intent intent = new Intent(MainActivity.this,NextActivity.class);
  95.                 startActivity(intent);
  96.                 break;

  97.         }

  98.         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
  99.         item.setChecked(true);
  100.         getSupportActionBar().setTitle(title);
  101.         assert drawer != null;
  102.         drawer.closeDrawer(GravityCompat.START);
  103.         return true;

  104.     }
  105. }
Customizing the ViewPager adapter based on FragmentPagerAdapter or FragmentStatePagerAdapter.

ViewPagerAdapter.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.support.v4.app.Fragment;
  3. import android.support.v4.app.FragmentManager;
  4. import android.support.v4.app.FragmentPagerAdapter;

  5. public class ViewPagerAdapter extends FragmentPagerAdapter {
  6.     public ViewPagerAdapter(FragmentManager fm) {
  7.         super(fm);
  8.     }

  9.     @Override
  10.     public Fragment getItem(int position) {
  11.         if (position ==0) {
  12.             return new FirstFragment();
  13.         }

  14.         else if (position == 1) {
  15.             return new SecondFragment();
  16.         }

  17.         else
  18.             return new ThirdFragment();
  19.     }

  20.     @Override
  21.     public int getCount() {
  22.         return 3;
  23.     }
  24. }
Now, we need to make the list item layout for RecyclerView. The layout code is as:

list_item.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.v7.widget.CardView
  3.     xmlns:android="http://schemas.android.com/apk/res/android"
  4.     xmlns:card_view="http://schemas.android.com/apk/res-auto"
  5.     android:id="@+id/cvItem"
  6.     android:layout_gravity="top"
  7.     android:layout_width="match_parent"
  8.     android:layout_height="65dp"
  9.     android:layout_marginBottom="4dp"
  10.     android:layout_marginLeft="8dp"
  11.     android:layout_marginRight="8dp"
  12.     android:layout_marginTop="4dp"
  13.     android:minHeight="65dp"
  14.     card_view:cardCornerRadius="10dp">

  15.     <LinearLayout
  16.         xmlns:android="http://schemas.android.com/apk/res/android"
  17.         android:id="@+id/text_container"
  18.         android:layout_width="match_parent"
  19.         android:layout_height="65dp"
  20.         android:minHeight="65dp"
  21.         android:gravity="center_vertical"
  22.         android:orientation="vertical">

  23.         <TextView
  24.             android:id="@+id/list_text"
  25.             android:text="text"
  26.             android:gravity="center_vertical"
  27.             android:layout_gravity="center"
  28.             android:paddingLeft="16dp"
  29.             android:textSize="16sp"
  30.             android:layout_width="match_parent"
  31.             android:layout_height="wrap_content"
  32.             android:textAppearance="?android:textAppearanceSmall"
  33.             android:textColor="@android:color/black"
  34.             android:textStyle="normal"/>
  35.     </LinearLayout>

  36. </android.support.v7.widget.CardView>
Now, We need to make the model for taking data in RecyclerView and adapter class also needs to be built for setting data into it and adding RecyclerView item one after the other.

RecyclerViewModel.java
  1. package test.ku.codedivas.sampleapp;

  2. public class RecyclerViewModel {

  3.     private String mItemName;

  4.     public RecyclerViewModel(String ItemName){
  5.         mItemName = ItemName;
  6.     }

  7.     public String getmItemName() {
  8.         return mItemName;
  9.     }
  10. }
RecyclerViewAdapter.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.support.v7.widget.CardView;
  6. import android.support.v7.widget.RecyclerView;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. import java.util.ArrayList;

  13. public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
  14.     private static final String LOG_TAG = RecyclerViewAdapter.class.getSimpleName();
  15.     private ArrayList<RecyclerViewModel> mItems;
  16.     ItemListener mListener;
  17.     Context context;
  18.     public static int position;

  19.     public RecyclerViewAdapter(Activity context, ArrayList<RecyclerViewModel> program, ItemListener listener) {

  20.         this.context = context;
  21.         mItems = program;
  22.         mListener = listener;
  23.     }

  24.     public void setOnItemClickListener(ItemListener listener) {
  25.         mListener = listener;
  26.     }

  27.     @Override
  28.     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  29.         View v = LayoutInflater
  30.                 .from(parent.getContext())
  31.                 .inflate(R.layout.list_item, parent, false);
  32.         context = parent.getContext();
  33.         return new ViewHolder(v);
  34.     }

  35.     @Override
  36.     public void onBindViewHolder(ViewHolder holder, int position) {
  37.         holder.setData(mItems.get(position));
  38.     }

  39.     @Override
  40.     public int getItemCount() {
  41.         if (mItems != null) {
  42.             return mItems.size();
  43.         }
  44.         return 0;
  45.     }

  46.     public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
  47.         public CardView cardView;
  48.         public RecyclerViewModel pName;
  49.         TextView name;
  50.         View textContainer;

  51.         public ViewHolder(View itemView) {

  52.             super(itemView);
  53.             itemView.setOnClickListener(this);
  54.             cardView = (CardView)itemView.findViewById(R.id.cvItem);
  55.             name = (TextView) itemView.findViewById(R.id.list_text);
  56.             textContainer = itemView.findViewById(R.id.text_container);
  57.         }

  58.         public void setData(RecyclerViewModel pName) {
  59.             this.pName = pName;
  60.             name.setText(pName.getmItemName());
  61.         }

  62.         @Override
  63.         public void onClick(View v) {
  64.             if (mListener != null) {
  65.                 mListener.onItemClick(pName, getAdapterPosition());
  66.             }
  67.             Toast.makeText(context,pName.getmItemName(),Toast.LENGTH_SHORT).show();

  68.         }

  69.     }

  70.     public interface ItemListener {
  71.         void onItemClick(RecyclerViewModel pName, int position);
  72.     }
  73. }
There are 3 fragments of ViewPager in this project.

FirstFragment.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.os.Bundle;
  3. import android.support.annotation.Nullable;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v7.widget.LinearLayoutManager;
  6. import android.support.v7.widget.RecyclerView;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;

  10. import java.util.ArrayList;

  11. public class FirstFragment extends Fragment {
  12.     @Nullable
  13.     @Override
  14.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  15.         View rootView = inflater.inflate(R.layout.fragment_layout,container, false);
  16.         return rootView;
  17.     }
  18.     @Override
  19.     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  20.         super.onViewCreated(view, savedInstanceState);

  21.         final ArrayList<RecyclerViewModel> pname = new ArrayList<RecyclerViewModel>();

  22.         pname.add(new RecyclerViewModel("Alpha"));
  23.         pname.add(new RecyclerViewModel("Beta"));
  24.         pname.add(new RecyclerViewModel("Cupcake"));
  25.         pname.add(new RecyclerViewModel("Donut"));
  26.         pname.add(new RecyclerViewModel("Eclairs"));
  27.         pname.add(new RecyclerViewModel("Froyo"));
  28.         pname.add(new RecyclerViewModel("GingerBread"));
  29.         pname.add(new RecyclerViewModel("HoneyComb"));
  30.         pname.add(new RecyclerViewModel("IceCreamSandwich"));
  31.         pname.add(new RecyclerViewModel("JellyBean"));
  32.         pname.add(new RecyclerViewModel("KitKat"));
  33.         pname.add(new RecyclerViewModel("Lollipop"));
  34.         pname.add(new RecyclerViewModel("MarshMallow"));
  35.         pname.add(new RecyclerViewModel("Nougat"));

  36.         final RecyclerViewAdapter itemsAdapter = new RecyclerViewAdapter(FirstFragment.this.getActivity(), pname, null);
  37.         final RecyclerView clv = (RecyclerView) view.findViewById(R.id.clist);
  38.         clv.setLayoutManager(new LinearLayoutManager(FirstFragment.this.getActivity()));
  39.         clv.setHasFixedSize(true);
  40.         clv.setAdapter(itemsAdapter);

  41.     }
  42.     }
SecondFragment.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.os.Bundle;
  3. import android.support.annotation.Nullable;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v7.widget.LinearLayoutManager;
  6. import android.support.v7.widget.RecyclerView;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;

  10. import java.util.ArrayList;

  11. public class SecondFragment extends Fragment {
  12.     @Nullable
  13.     @Override
  14.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  15.         View rootView = inflater.inflate(R.layout.fragment_layout,container, false);
  16.         return rootView;
  17.     }
  18.     @Override
  19.     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  20.         super.onViewCreated(view, savedInstanceState);

  21.         final ArrayList<RecyclerViewModel> pname = new ArrayList<RecyclerViewModel>();

  22.         pname.add(new RecyclerViewModel("Alpha"));
  23.         pname.add(new RecyclerViewModel("Beta"));
  24.         pname.add(new RecyclerViewModel("Cupcake"));
  25.         pname.add(new RecyclerViewModel("Donut"));
  26.         pname.add(new RecyclerViewModel("Eclairs"));
  27.         pname.add(new RecyclerViewModel("Froyo"));
  28.         pname.add(new RecyclerViewModel("GingerBread"));
  29.         pname.add(new RecyclerViewModel("HoneyComb"));
  30.         pname.add(new RecyclerViewModel("IceCreamSandwich"));
  31.         pname.add(new RecyclerViewModel("JellyBean"));
  32.         pname.add(new RecyclerViewModel("KitKat"));
  33.         pname.add(new RecyclerViewModel("Lollipop"));
  34.         pname.add(new RecyclerViewModel("MarshMallow"));
  35.         pname.add(new RecyclerViewModel("Nougat"));
  36.         final RecyclerViewAdapter itemsAdapter = new RecyclerViewAdapter(SecondFragment.this.getActivity(), pname, null);
  37.         final RecyclerView clv = (RecyclerView) view.findViewById(R.id.clist);
  38.         clv.setLayoutManager(new LinearLayoutManager(SecondFragment.this.getActivity()));
  39.         clv.setHasFixedSize(true);
  40.         clv.setAdapter(itemsAdapter);

  41.     }
  42. }
ThirdFragment.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.os.Bundle;
  3. import android.support.annotation.Nullable;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v7.widget.LinearLayoutManager;
  6. import android.support.v7.widget.RecyclerView;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import java.util.ArrayList;

  11. public class ThirdFragment extends Fragment {
  12.     @Nullable
  13.     @Override
  14.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  15.         View rootView = inflater.inflate(R.layout.fragment_layout,container, false);
  16.         return rootView;
  17.     }
  18.     @Override
  19.     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  20.         super.onViewCreated(view, savedInstanceState);

  21.         final ArrayList<RecyclerViewModel> pname = new ArrayList<RecyclerViewModel>();

  22.         pname.add(new RecyclerViewModel("Alpha"));
  23.         pname.add(new RecyclerViewModel("Beta"));
  24.         pname.add(new RecyclerViewModel("Cupcake"));
  25.         pname.add(new RecyclerViewModel("Donut"));
  26.         pname.add(new RecyclerViewModel("Eclairs"));
  27.         pname.add(new RecyclerViewModel("Froyo"));
  28.         pname.add(new RecyclerViewModel("GingerBread"));
  29.         pname.add(new RecyclerViewModel("HoneyComb"));
  30.         pname.add(new RecyclerViewModel("IceCreamSandwich"));
  31.         pname.add(new RecyclerViewModel("JellyBean"));
  32.         pname.add(new RecyclerViewModel("KitKat"));
  33.         pname.add(new RecyclerViewModel("Lollipop"));
  34.         pname.add(new RecyclerViewModel("MarshMallow"));
  35.         pname.add(new RecyclerViewModel("Nougat"));

  36.         final RecyclerViewAdapter itemsAdapter = new RecyclerViewAdapter(ThirdFragment.this.getActivity(), pname, null);
  37.         final RecyclerView clv = (RecyclerView) view.findViewById(R.id.clist);
  38.         clv.setLayoutManager(new LinearLayoutManager(ThirdFragment.this.getActivity()));
  39.         clv.setHasFixedSize(true);
  40.         clv.setAdapter(itemsAdapter);

  41.     }
  42. }
In order to show Recycler View in each fragment of ViewPager, the layout code should be like this:

fragment_layout.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.v7.widget.RecyclerView
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     android:id="@+id/clist"
  8.     android:drawSelectorOnTop="true"
  9.     android:background="#D0D0D0"
  10.     app:layout_scrollFlags="scroll|enterAlways"
  11.     app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Now, when we need to call next activity on sliding menu item click then we need to create new Activity and its layout and call it from MainActivity of sliding menu (Navigation Drawer).

The code for new activity should be like this:

NextActivity.java
  1. package test.ku.codedivas.sampleapp;

  2. import android.support.v7.app.AppCompatActivity;
  3. import android.os.Bundle;

  4. public class NextActivity extends AppCompatActivity {

  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         setContentView(R.layout.activity_next);

  9.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  10.     }

  11.  @Override 
  12. public void onBackPressed() {
  13. finish();
  14. }
  15. }
In layout file, any layout can be created according the user.

The code for layout could be like this:

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

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:id="@+id/activity_next"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     android:layout_gravity="center_vertical"
  7.     android:gravity="center_vertical"
  8.     android:orientation="vertical">

  9.     <TextView
  10.         android:id="@+id/tv1"
  11.         android:layout_width="match_parent"
  12.         android:layout_height="wrap_content"
  13.         android:text="Hi"
  14.         android:gravity="center"
  15.         android:textSize="40sp"/>

  16.     <TextView
  17.         android:layout_width="match_parent"
  18.         android:layout_height="wrap_content"
  19.         android:gravity="center"
  20.         android:text="Inside NextActivity"
  21.         android:textSize="30sp"/>

  22. </LinearLayout>

Note: In this project, I use Toolbar as ActionBar, so the project theme is "No Action Bar" theme.

styles.xml
  1. <resources>

  2. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  3. <!-- Customize your theme here. -->
  4. <item name="colorPrimary">@color/colorPrimary</item>
  5. <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
  6. <item name="colorAccent">@color/colorAccent</item>
  7. </style>

  8. </resources>
The manifest file should be like this:

AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="test.ku.codedivas.sampleapp">

  4.     <application
  5.         android:allowBackup="true"
  6.         android:icon="@mipmap/ic_launcher"
  7.         android:label="@string/app_name"
  8.         android:supportsRtl="true"
  9.         android:theme="@style/AppTheme">
  10.         <activity
  11.             android:name=".MainActivity"
  12.             android:label="@string/app_name"
  13.             android:theme="@style/AppTheme.NoActionBar">
  14.             <intent-filter>
  15.                 <action android:name="android.intent.action.MAIN" />
  16.                 <category android:name="android.intent.category.LAUNCHER" />
  17.             </intent-filter>
  18.         </activity>
  19.         <activity android:name=".NextActivity"
  20.             android:label="@string/activityname"
  21.             android:parentActivityName=".MainActivity">
  22.             <meta-data
  23.                 android:name="android.support.PARENT_ACTIVITY"
  24.                 android:value=".MainActivity"/>
  25.         </activity>
  26.     </application>

  27. </manifest>

Running Application

Demo Video :


Output should be like: 

On clicking at the NavigationView's list item:



Toast Method on clicking the RecyclerView item:



On clicking at the NavigationView's list item and calling Next Activity:







Conclusions

Through this post, I hope you could learn about  combining the popular and powerful widgets in developing Android Application. Further, you can subscribe my blog  to get the newest tutorials..!

28 comments:

  1. thanks for the Combining Navigation Drawer and RecyclerView in ViewPager Fragments(with Tab) in one screen,
    I tried and its working
    waiting for your future post

    ReplyDelete
  2. app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

    getiing errorr

    ReplyDelete
  3. can u plz uload full source code

    ReplyDelete
    Replies
    1. Hi Rushi,
      Please check the updated code and let me know if you still get an error.

      Thanks

      Delete
  4. protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pagerdrawer);

    no layout pagerdrawer

    ReplyDelete
    Replies
    1. Hi Rahmat,

      Layout pagerdrawer is to be replaced with activity_main layout. Please check. Thanks

      Delete
  5. thanks CodeDivas, but i still get force close when i click nextactivity in navigation drawer,could u check it again and give the solution?

    ReplyDelete
    Replies
    1. Code is completely working fine. Could you let me know What error you are getting?

      Delete
  6. Replies
    1. Hi Atul,
      This post is related to provide an idea to add content in recyclerView Listitem, not about extracting the data from server and then displaying it in recyclerView.
      I would try to cover up your suggestion in my next post.

      Thanks!

      Delete
  7. How to add content inside that recycler view

    ReplyDelete
    Replies
    1. Hi,
      I'm not able to get your question but according to my understanding you might be asking about adding text or any other content in recyclerView. So, firstly, manipulate the list_item.xml file only according to your requirement.
      Make a model of the contents( like string or integer variables) you want to show in recyclerview list item then in the Activity(or fragment) make an arraylist of your model type.
      Using the same reference variable of that arraylist, you can call add() method to add different data items accordingly.

      In my case, I add only one textview in list_item.xml file and use it in RecyclerViewModel as String variable. Then, in Activity, I used that variable to add different contents like:

      final ArrayList pname = new ArrayList();

      pname.add(new RecyclerViewModel("Tomato")); // passing the string value to model. you can pass multiple values as parameters according to the number of parameters of your Model constructor
      pname.add(new RecyclerViewModel("Potato"));


      Hope it's helpful to you.

      Thanks

      Delete
  8. nice! big help! could please show us how to filter those items in the recyclerview using searchview? a searchview that will work in all tabs. thanks a lot!

    ReplyDelete
    Replies
    1. Hi Jiren,

      You can refer to http://searchonrecyclerviewbycodedivas.blogspot.co.uk/2017/04/search-on-recyclerview-having-cardview.html to filter those items in the recyclerview using searchview.

      Delete
  9. thanks for the Combining Navigation Drawer and RecyclerView in ViewPager Fragments(with Tab) in one screen,
    I tried and its working but i want with Actionbar iam using your code but its not showing the actionbar.please help me
    waiting for your future post

    ReplyDelete
  10. R.string.navigation_drawer_open, R.string.navigation_drawer_close

    how to fix this redline?

    ReplyDelete
    Replies
    1. In string.xml, add a string name for navigation_drawer_open and navigation_drawer_close.

      Delete
    2. hay, im confusing, how to open other activity for every recycler view we click?

      Delete
  11. hello friend, very good job, it would be possible to add icons to the tablayout thanks a big hello

    ReplyDelete
  12. Theres error in toolbar
    check the image here :
    https://ibb.co/H7GLVRh
    please reply

    ReplyDelete
  13. java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
    error in nextactivity

    ReplyDelete
  14. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. Viking Freezer Repair in Los Angeles

    ReplyDelete
  15. The Best Casinos in Canada | List of All The Best Online Casinos
    Top casinos from every Canadian luckyclub to choose a top Canadian online casino that's a winner of the prestigious EGR SuperBook of the Year award.

    ReplyDelete

Add Search filter on Recycler View with CardView layout

In android development, this is about implementing the search filter with Edittext widget on  RecyclerView    having  CardView  layout. ...

Popular Posts