Tab View Inside Navigation Drawer for android

To create a project that displays Tab View inside navigation drawer selection. By simple step by step process. It’s simple to combine tab view inside navigation drawer. First start by creating a “Navigation Drawer Activity” in android studio (assuming you are aware of those things). Second part is to create a fragments to handle the navigation drawer activities.
This flow chart may help you to better understand what we want to achieve.
FragmentA contains the Tablayout (Tab View) and view pager, the navigation drawer pass id to FragmentA it displays tabs and content to be displayed in the viewpager according to the navigation drawer and tab selected. In this case the id passed is the name of navigation drawer menu.
This project contains.
MainActivity.java => Navigation Drawer Activity.
FragmentA.java => Fragment containing Tab View.
FragmentB.java => Fragment for viewpager.
FragmentC.java => Fragment for running first and menu without tabs.
Constants.java => Class file for keeping constant values.
SectionsPageAdapter.java => It’s a Fragment Page Adapter to handle FragmentB from FragmentA.
OnFragmentInteractionListener.java => for handling communication between Fragment and parent activity.
Below is a simple step by step explanation.
1.Constants.java
This class contain only key values for passing data to fragments.
public class Constants { public final static String FRAG_A="fragment_a"; public final static String FRAG_B="fragment_b"; public final static String FRAG_C="fragment_c"; }
2.OnFragmentInteractionListener.java
A simple interface for communicating between fragments and parent activity.
public interface OnFragmentInteractionListener { public void onFragmentMessage(int TAG, String data); }
3. FragmentC.java
This fragment is only for displaying message of those menu that don’t have any tabs. The arguments are the name of navigation menu name (id).
public class FragmentC extends Fragment { private OnFragmentInteractionListener mListener; private TextView text_view_for_normal_selection; public FragmentC() { // Required empty public constructor } public static FragmentC newInstance(String normalText) { FragmentC fragment = new FragmentC(); Bundle args = new Bundle(); args.putString(Constants.FRAG_C, normalText); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_c, container, false); text_view_for_normal_selection=(TextView)view.findViewById(R.id.text_view_for_normal_selection); text_view_for_normal_selection.setText(getArguments().getString(Constants.FRAG_C)); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onResume() { super.onResume(); } }
fragment_c.xml
<FrameLayout 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" tools:context="logicchip.tabwithnavigation.FragmentC"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:layout_gravity="center" android:textColor="@color/colorAccent" android:id="@+id/text_view_for_normal_selection" android:text="@string/hello_blank_fragment" /> </FrameLayout>
4. FragmentB.java
FragmentB is for displaying the contents of the tab selected. The arguments are the name of the selected tabs (id).
public class FragmentB extends Fragment { private OnFragmentInteractionListener mListener; private TextView text_view_for_tab_selection; public FragmentB() { // Required empty public constructor } public static FragmentB newInstance(String tabSelected) { FragmentB fragment = new FragmentB(); Bundle args = new Bundle(); args.putString(Constants.FRAG_B, tabSelected); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_b, container, false); text_view_for_tab_selection=(TextView)view.findViewById(R.id.text_view_for_tab_selection); text_view_for_tab_selection.setText(getArguments().getString(Constants.FRAG_B)); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onResume() { super.onResume(); } }
fragment_b.xml
<FrameLayout 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" tools:context="logicchip.tabwithnavigation.FragmentB"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:textColor="@color/colorAccent" android:layout_gravity="center" android:id="@+id/text_view_for_tab_selection" android:text="@string/hello_blank_fragment" /> </FrameLayout>
5. SectionsPageAdapter.java
This class file is an adapter for handling instance of tabs selected, which displays contents of FragmentB according to the tab selected. It extents FragmentPagerAdapter class.
public class SectionsPagerAdapter extends FragmentPagerAdapter { int mNumOfTabs; ArrayList<String> tabName; public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs, ArrayList<String> tabName) { super(fm); this.mNumOfTabs = NumOfTabs; this.tabName=tabName; } @Override public Fragment getItem(int position) { FragmentB comn=new FragmentB(); return comn.newInstance(tabName.get(position)); } @Override public int getCount() { return mNumOfTabs; } }
6. FragmentA.java
This fragment contains tablayout and viewpager. FragmentB is displayed inside viewpager. FragmentA is placed inside the parent activity, so when clicking a menu item it displays Parent Activity and inside it FragmentA with Tabs and Viewpager also FragmentB inside Viewpager.
This figure shows how it’s implemented.
public class FragmentA extends Fragment { private TabLayout tabLayout; private ViewPager mViewPager; private OnFragmentInteractionListener mListener; private SectionsPagerAdapter mSectionsPagerAdapter; ArrayList<String> tabName; public FragmentA() { // Required empty public constructor } public static FragmentA newInstance(String navigation) { FragmentA fragment = new FragmentA(); Bundle args = new Bundle(); args.putString(Constants.FRAG_A, navigation); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_a, container, false); tabLayout = (TabLayout)view.findViewById(R.id.tabs); mViewPager = (ViewPager)view.findViewById(R.id.container); tabName=new ArrayList<String>(); for(int i=0;i<7;i++){ tabLayout.addTab(tabLayout.newTab().setText(getArguments().getString(Constants.FRAG_A)+" "+String.valueOf(i))); tabName.add(getArguments().getString(Constants.FRAG_A)+" "+String.valueOf(i)); } tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); getChildFragmentManager().beginTransaction().addToBackStack(null).commit(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Note that we are passing childFragmentManager, not FragmentManager mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName); mViewPager.setAdapter(mSectionsPagerAdapter); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onResume() { super.onResume(); } }
fragment_a.xml
<FrameLayout 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="logicchip.tabwithnavigation.FragmentA"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" android:theme="@style/AppTheme.AppBarOverlay"/> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> </LinearLayout> </FrameLayout>
7. MainActivity.java
The mainactivity.java is the launcher activity (parent activity) it implements navigation item selected listener and OnFragmentInteractionListener (our 2nd step mentioned above). Coding take place in the “onNavigationItemSelected (MenuItem item)” method, handling the menu items clicks. Another method name “homeFragment ()” is also created to display when starting up otherwise we get a blank screen when starting. Back pressed method “onBackPressed ()” is slightly modified to handle back click for selected drawer menu item. All the other things we need are already included in the template “Navigation Drawer Activity in Android Studio”.
Because it’s Navigation Drawer it contains more than one xml file.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,OnFragmentInteractionListener { private CoordinatorLayout coordinatorLayout; private ActionBarDrawerToggle toggle; private boolean mToolBarNavigationListenerIsRegistered = false; private FloatingActionButton fab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); coordinatorLayout=(CoordinatorLayout)findViewById(R.id.coordinatorLayout); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SnackBarMessage("Happy coding."); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); homeFragment(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else if(getFragmentManager().getBackStackEntryCount()>0){ getFragmentManager().popBackStack(); }else{ super.onBackPressed(); } } public void SnackBarMessage(String message){ Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Fragment fragment = null; Class fragmentClass = null; Bundle args = new Bundle(); switch (id){ case R.id.nav_1:fragmentClass =FragmentA.class;args.putString(Constants.FRAG_A,"Import");break; case R.id.nav_2:fragmentClass =FragmentA.class;args.putString(Constants.FRAG_A,"Gallery");break; case R.id.nav_3:fragmentClass =FragmentA.class;args.putString(Constants.FRAG_A,"Slideshow");break; case R.id.nav_4:fragmentClass =FragmentA.class;args.putString(Constants.FRAG_A,"Tools");break; case R.id.nav_5:fragmentClass =FragmentC.class;args.putString(Constants.FRAG_C,"Share");break; case R.id.nav_6:fragmentClass =FragmentC.class;args.putString(Constants.FRAG_C,"Send");break; } try { fragment = (Fragment) fragmentClass.newInstance(); fragment.setArguments(args); // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.fragment_layout_for_activity_navigation, fragment).addToBackStack(null).commit(); } catch (Exception e) { e.printStackTrace(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onFragmentMessage(int TAG, String data) { } public void homeFragment(){ try { Bundle args = new Bundle(); Class fragmentClass =FragmentC.class;args.putString(Constants.FRAG_C,"Welcome"); Fragment fragment = (Fragment) fragmentClass.newInstance(); fragment.setArguments(args); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.fragment_layout_for_activity_navigation, fragment).commit(); } catch (Exception e) { e.printStackTrace(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } }
app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:id="@+id/coordinatorLayout" tools:context="logicchip.tabwithnavigation.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <!-- <include layout="@layout/content_main" /> --> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="logicchip.tabwithnavigation.MainActivity" tools:showIn="@layout/app_bar_main" android:id="@+id/fragment_layout_for_activity_navigation" > </FrameLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/btn_star_big_on" /> </android.support.design.widget.CoordinatorLayout>
Download full source code for free