V-navigation-drawer With V-app-bar

Today's tutorial is Android Navigation Drawer With Fragments And Material Design Example.

1. Android Custom Navigation Drawer Example

2. Android Navigation Drawer With Toolbar/Actionbar Menu Items

3. Navigation Drawer Android Studio With Nested Fragment

1. Android Navigation Drawer Example | Custom Drawer

Android Navigation Drawer with fragments example guides you to create a sliding navigation menu with recyclerview.

Android Navigation Drawer with fragments tutorial uses fragments for navigation purpose.

You may have seen some application in which, when choose different options from navigation drawer, action bar shows different icons and labels for every particular fragment.

First, check the output and then follow all the steps.

Step 2: Update build.gradle(Module:app) file

Add below in build.gradle(Module:app) file

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

Final code forbuild.gradle(Module:app)

apply plugin: 'com.android.application'  android {     compileSdkVersion 23     buildToolsVersion "23.0.3"      defaultConfig {         applicationId "com.exampledemo.parsaniahardik.drawerbasicdemonuts"         minSdkVersion 16         targetSdkVersion 22         versionCode 1         versionName "1.0"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:4.12'     compile 'com.android.support:appcompat-v7:23.4.0'     compile 'com.android.support:recyclerview-v7:23.2.1' }        

Step 3: Preparing two fragments

Create two fragments and give them name as "FriendListFragment" and "NotificationFragment."

Add below code in fragment_friend_list.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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.FriendListFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="30sp"         android:background="#4aef44"         android:textColor="#fff"         android:text="Friends List" />  </FrameLayout>        

Add below code inFriendListFragment.java

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  public class FriendListFragment extends Fragment {      public FriendListFragment() {         // Required empty public constructor     }     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);      }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.fragment_friend_list, container, false);     }  }

Copy following source code in fragment_notification.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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.NotificationFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="30sp"         android:background="@color/colorAccent"         android:textColor="#fff"         android:text="Notification" />  </FrameLayout>        

Copy following code inNotificationFragment.java

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  public class NotificationFragment extends Fragment {      public NotificationFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.fragment_notification, container, false);     } }

Step 4: Adding images

Download images and copy them into "drawable" directory.

Download icons

Step 5: Updating strings.xml and styles.xml

Update string.xml as per below code

<resources>     <string name="app_name">DrawerBasicDemonuts</string>      <!-- TODO: Remove or change this placeholder text -->     <string name="drawer_open">Open</string>     <string name="drawer_close">Close</string>     <string name="hello_blank_fragment">Hello blank fragment</string> </resources>        

Update styles.xml as following

<resources>     <!-- Base application theme. -->     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">         <!-- Customize your theme here. -->         <item name="windowNoTitle">true</item>         <item name="windowActionBar">false</item>         <item name="colorPrimary">@color/colorPrimary</item>         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>         <item name="colorAccent">@color/colorAccent</item>     </style>  </resources>        

Step 6: Adding toolbar.xml

Create new layout resource file and give it name as "toolbar.xml"

Copy below source code in it.

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:local="http://schemas.android.com/apk/res-auto"     android:id="@+id/toolbar"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:minHeight="?attr/actionBarSize"     android:background="?attr/colorPrimary"     local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"     local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Step 7: Creating lv_item.xml file

Make a new layout resource file named "lv_item.xml"

This file is a recyclerview item file. Add below code in it

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="horizontal"     android:clickable="true">      <ImageView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/ivicon"         android:layout_marginLeft="5dp"         android:layout_marginTop="5dp"         android:src="@drawable/notification"/>      <TextView         android:id="@+id/name"         android:layout_width="wrap_content"         android:layout_height="35dp"         android:paddingLeft="10dp"         android:paddingTop="7dp"         android:text="Noti"         android:paddingBottom="10dp"         android:textSize="15dp"         android:textStyle="bold" />  </LinearLayout>

Step 8: Creating Model

Create a new Java class named "DrawerModel" and add following code

public class DrawerModel {      private String name;     private int image;      public int getImage() {         return image;     }      public void setImage(int image) {         this.image = image;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     } }        

Step 9: Making Recyclerview Adapter

Create a new Java class named "DrawerAdapter" and paste below code

import android.content.Context; import android.view.LayoutInflater; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList;  public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {      ArrayList<DrawerModel> arrayList = new ArrayList<>();     private LayoutInflater inflater;     private Context context;      public DrawerAdapter(Context context,  ArrayList<DrawerModel> arrayList) {         this.context = context;         inflater = LayoutInflater.from(context);         this.arrayList = arrayList;     }      @Override     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View view = inflater.inflate(R.layout.lv_item, parent, false);         ViewHolder holder = new ViewHolder(view);         return holder;     }      @Override     public void onBindViewHolder(ViewHolder holder, int position) {          holder.title.setText(arrayList.get(position).getName());         holder.ivicon.setImageResource(arrayList.get(position).getImage());     }      @Override     public int getItemCount() {         return arrayList.size();     }      class ViewHolder extends RecyclerView.ViewHolder {         TextView title;         ImageView ivicon;          public ViewHolder(View itemView) {             super(itemView);             title = (TextView) itemView.findViewById(R.id.name);             ivicon = (ImageView) itemView.findViewById(R.id.ivicon);         }     } }

Step 10: Creating DrawerFragment

Make a new fragment named DrawerFragment.

Add below source code in fragment_drawer.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:background="#e45a2c">      <RelativeLayout         android:id="@+id/nav_header_container"         android:layout_width="match_parent"         android:layout_height="150dp"         android:layout_alignParentTop="true"         android:background="#4fe7ec">          <ImageView             android:layout_width="70dp"             android:layout_height="70dp"             android:src="@mipmap/ic_launcher"             android:scaleType="fitCenter"             android:layout_centerInParent="true" />      </RelativeLayout>       <android.support.v7.widget.RecyclerView         android:id="@+id/listview"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="15dp" />   </LinearLayout>

Add following source code into DrawerFragment.java

import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList;  public class DrawerFragment extends Fragment {      private View view;     private ActionBarDrawerToggle mDrawerToggle;     private DrawerLayout mDrawerLayout;     private DrawerAdapter drawerAdapter;     private View containerView;     private RecyclerView recyclerView;     private String[] names = new String[]{"Friends List", "Notification" };     private int[] images = new int[]{R.drawable.friendlist, R.drawable.notification};      public DrawerFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);      }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         view = inflater.inflate(R.layout.fragment_drawer, container, false);         recyclerView = (RecyclerView) view.findViewById(R.id.listview);         drawerAdapter = new DrawerAdapter(getActivity(),populateList());          recyclerView.setAdapter(drawerAdapter);         recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));         recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {             @Override             public void onClick(View view, int position) {                 openFragment(position);                 mDrawerLayout.closeDrawer(containerView);             }              @Override             public void onLongClick(View view, int position) {              }         }));          openFragment(0);          return view;     }      private void openFragment(int position) {          switch (position) {             case 0:                 removeAllFragment(new FriendListFragment(), "Friends");                 break;             case 1:                 removeAllFragment(new NotificationFragment(), "Notifiaction");                 break;              default:                 break;         }     }      public void removeAllFragment(Fragment replaceFragment, String tag) {         FragmentManager manager = getActivity().getSupportFragmentManager();         FragmentTransaction ft = manager.beginTransaction();         manager.popBackStackImmediate(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);          ft.replace(R.id.container_body, replaceFragment);         ft.commitAllowingStateLoss();     }      public void setUpDrawer(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {         containerView = getActivity().findViewById(fragmentId);         mDrawerLayout = drawerLayout;         mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open , R.string.drawer_close ) {             @Override             public void onDrawerOpened(View drawerView) {                 super.onDrawerOpened(drawerView);                 getActivity().invalidateOptionsMenu();             }              @Override             public void onDrawerClosed(View drawerView) {                 super.onDrawerClosed(drawerView);                 getActivity().invalidateOptionsMenu();             }              @Override             public void onDrawerSlide(View drawerView, float slideOffset) {                 super.onDrawerSlide(drawerView, slideOffset);                 toolbar.setAlpha(1 - slideOffset / 2);             }         };          mDrawerLayout.setDrawerListener(mDrawerToggle);         mDrawerLayout.post(new Runnable() {             @Override             public void run() {                 mDrawerToggle.syncState();             }         });      }      private ArrayList<DrawerModel> populateList(){          ArrayList<DrawerModel> list = new ArrayList<>();          for(int i = 0; i < names.length; i++){             DrawerModel drawerModel = new DrawerModel();             drawerModel.setName(names[i]);             drawerModel.setImage(images[i]);             list.add(drawerModel);         }         return list;     }      public interface ClickListener {          void onClick(View view, int position);           void onLongClick(View view, int position);     }      static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {          private GestureDetector gestureDetector;         private ClickListener clickListener;          public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {             this.clickListener = clickListener;             gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {                 @Override                 public boolean onSingleTapUp(MotionEvent e) {                     return true;                 }                  @Override                 public void onLongPress(MotionEvent e) {                     View child = recyclerView.findChildViewUnder(e.getX(), e.getY());                     if (child != null && clickListener != null) {                         clickListener.onLongClick(child, recyclerView.getChildPosition(child));                     }                 }             });         }          @Override         public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {              View child = rv.findChildViewUnder(e.getX(), e.getY());             if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {                 clickListener.onClick(child, rv.getChildPosition(child));             }             return false;         }          @Override         public void onTouchEvent(RecyclerView rv, MotionEvent e) {         }          @Override         public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {          }     } }

Step 11: Description of DrawerFragment.java

In onCreateView() method, recyclerview is initialized and its onClick() method is implemented.

For recyclerview's onClick() method implementation, a class named RecycletTouchListener and an interface named ClickListener is defined.

openFragment() method will open fragment. Here, aremoveAllFragment() method is used to remove all fragments from back stack and open a fresh new fragment.

setUpDrawer() method will be used in MainActivity.

Step 12: Updating MainActivity

Copy below code into activity_main.xml

<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"     android:layout_width="match_parent"     android:layout_height="match_parent">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">          <LinearLayout             android:id="@+id/container_toolbar"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:orientation="vertical">              <include                 android:id="@+id/toolbar"                 layout="@layout/toolbar" />         </LinearLayout>          <FrameLayout             android:id="@+id/container_body"             android:layout_width="fill_parent"             android:layout_height="0dp"             android:layout_weight="1" />     </LinearLayout>     <fragment         android:id="@+id/fragment_navigation_drawer"         android:name="com.exampledemo.parsaniahardik.drawerbasicdemonuts.DrawerFragment"         android:layout_width="260dp"         android:layout_height="match_parent"         android:layout_gravity="start"         app:layout="@layout/fragment_drawer"         tools:layout="@layout/fragment_drawer" />  </android.support.v4.widget.DrawerLayout>

Update MainActivity.java as per following

import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar;  public class MainActivity extends AppCompatActivity {      private Toolbar toolbar;     private DrawerFragment drawerFragment;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          toolbar = (Toolbar) findViewById(R.id.toolbar);          setSupportActionBar(toolbar);         getSupportActionBar().setDisplayShowHomeEnabled(true);         drawerFragment = (DrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);         drawerFragment.setUpDrawer(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);     } }        

The End for Navigation Drawer In Android Studio example.





Android navigation drawer will add menu items in toolbar or action bar or header bar.

Android navigation drawer example guides to show different menu items in the toolbar or actionbar for a different fragment.

Complete all the steps from the above example, then follow steps of this tutorial.

First, watch the output of Android navigation drawer example, then we will prepare it.

Step 1: Follow all the steps from above example.

After you have completed above android sliding navigation drawer tutorial, you will have one android project with navigation drawer.

This step is must so make sure you have complete working project made from above tutorial.

Now follow below steps.

Step 2: Adding images to drawable

Download images and copy them into "drawable" directory.

Download message_icon

Step 3: Creating menu resource directory

Create a new resource directory named "menu" inside the "res" directory as per below image.

android navigation drawer

Inside "menu," make two xml files and name them as friend_menu.xml and notification_menu.xml

Add below source code infriend_menu.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/action_message"         android:orderInCategory="100"         android:title="Message"         android:icon="@drawable/message"         app:showAsAction="always" />     <item         android:id="@+id/action_block"         android:orderInCategory="100"         android:title="Block"         app:showAsAction="always" />  </menu>

Copy following innotification_menu.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/action_update"         android:orderInCategory="100"         android:title="Update Profile"         app:showAsAction="never" />     <item         android:id="@+id/action_logout"         android:orderInCategory="100"         android:title="Logout"         app:showAsAction="never" /> </menu>

Step 4: Updating FriendListFragment

Update FriendListFragment.javaas below

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast;  public class FriendListFragment extends Fragment {      public FriendListFragment() {         // Required empty public constructor     }     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);        setHasOptionsMenu(true);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.fragment_friend_list, container, false);     }      @Override     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {          inflater.inflate(R.menu.friend_menu, menu);          super.onCreateOptionsMenu(menu, inflater);     }      @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_message) {             Toast.makeText(getActivity(), "Message clicked!", Toast.LENGTH_SHORT).show();             return true;          }else if(id == R.id.action_block){             Toast.makeText(getActivity(), "Block clicked!", Toast.LENGTH_SHORT).show();             return true;         }          return super.onOptionsItemSelected(item);     }  }

Step 5: Describing update

In onCreate() method, setHasOptionsMenu() is called.

This method is necessary for implementing menu items in Toolbar.

This method must be present in the every fragments for which you want options in actionbar.

Two methods are override. One is onCreateOptionsMenu() and second is onOptionsItemSelected()

Step 6: Updating NotificationFragment

Replace source code of NotificationFragment with following

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast;  public class NotificationFragment extends Fragment {      public NotificationFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setHasOptionsMenu(true);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.fragment_notification, container, false);     }      @Override     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {          inflater.inflate(R.menu.notification_menu, menu);          super.onCreateOptionsMenu(menu, inflater);     }      @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_update) {             Toast.makeText(getActivity(), "Update clicked!", Toast.LENGTH_SHORT).show();             return true;          }else if(id == R.id.action_logout){             Toast.makeText(getActivity(), "Logout clicked!", Toast.LENGTH_SHORT).show();             return true;         }          return super.onOptionsItemSelected(item);     }  }

This small demo is the base for every application for all your future applications in which you want different menu items in toolbar or action bar for each fragment.

You also have access to onclick method of every items of toolbar. You can put logic in this onclick method.





3. Navigation Drawer Android Studio With Nested Fragment

Navigation drawer Android Studio example guide you to create a nested fragment.

Navigation drawer Android example will give you a professional structure to create an Android app with child fragment and sliding menu.

Complete all the steps from that example then follow steps of this tutorial.

First, see the output of navigation drawer android studio example, then we will make it.

Step 1: Follow all the steps from basic navigation drawer in Android tutorial.

After you have completed above tutorial, you will have one android project with navigation drawer.

Now follow below steps.

Step 2: Creating FriendActivity

Make a new activity named "FriendActivity."

Copy below code into the FriendActivity.java

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem;  public class FriendActivity extends AppCompatActivity {      private Toolbar toolbar;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_friend);          toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          getSupportActionBar().setTitle("Friend Activity");        // getSupportActionBar().setHomeAsUpIndicator(R.mipmap.backarrow);         getSupportActionBar().setDisplayHomeAsUpEnabled(true);     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         if (item.getItemId() == android.R.id.home) {             onBackPressed();             return true;         }         return false;     } }        

Add following code into activity_friend.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical"     tools:context="com.exampledemo.parsaniahardik.drawerfragmentdemonuts.FriendActivity">      <include         layout="@layout/toolbar"         android:id="@+id/toolbar"     />      <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="25sp"         android:textColor="#fff"         android:background="#e76d30"         android:id="@+id/tv"         android:text="Friend Activity" />  </LinearLayout>        

Step 3: Adding FriendNested Fragment

Create a new fragment and give the name as "FriendNestedFragment."

Add below code in fragment_friend_nested.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="com.exampledemo.parsaniahardik.drawerfragmentdemonuts.FriendNestedFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="25sp"         android:textColor="#fff"         android:background="#4244d6"         android:id="@+id/tv"         android:text="Friend Nested Fragment" />  </FrameLayout>        

Copy below source code in FriendNestedFragment.java

import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  public class FriendNestedFragment extends Fragment {      private View view;     private TextView textView;      public FriendNestedFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);      }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         view = inflater.inflate(R.layout.fragment_friend_nested, container, false);          textView = (TextView) view.findViewById(R.id.tv);          textView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 Intent intent = new Intent(getActivity(),FriendActivity.class);                 startActivity(intent);             }         });          return view;     } }

Step 4: Updating FriendListFragment

Update fragment_friend_list.xml as per below

<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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.FriendListFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/tvfriend"         android:gravity="center"         android:textSize="30sp"         android:background="#4aef44"         android:textColor="#fff"         android:text="Friends List" />  </FrameLayout>

Update FriendListFragment.java

import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  public class FriendListFragment extends Fragment {      private TextView tvfriend;     private View view;      public FriendListFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         view = inflater.inflate(R.layout.fragment_friend_list, container, false);         tvfriend = (TextView) view.findViewById(R.id.tvfriend);          tvfriend.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 addFragment(new FriendNestedFragment(),"Nested");             }         });          return view;     }     public void addFragment(Fragment fragment, String tag) {         FragmentManager manager = getActivity().getSupportFragmentManager();         FragmentTransaction ft = manager.beginTransaction();         ft.addToBackStack(tag);         ft.replace(R.id.container_body, fragment, tag);         ft.commitAllowingStateLoss();     } }

Description of addFragment() method

This method will open a new fragment in the container box.

This method will put the fragment in the backstack before opening it. That means when the user clicks on the back button this fragment will be open if new any nested fragment or activity is opened.

Here, we have opened a FriendActivity,so when you come back from theFriendActivity, FriendNestedFragmentwill be opened as shown in the output video.

Step 5: Creating NotiSecondNestedFragment

Prepare a new fragment named NotiSecondNestedFragment.

Copy below source code in fragment_noti_second_nested.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="com.exampledemo.parsaniahardik.drawerfragmentdemonuts.NotiSecondNestedFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="25sp"         android:textColor="#fff"         android:background="#198f07"         android:id="@+id/tv"         android:text="Notification Second Nested Fragment" />  </FrameLayout>        

Add following inNotiSecondNestedFragment.java

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  public class NotiSecondNestedFragment extends Fragment {      private View view;      public NotiSecondNestedFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);      }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         view = inflater.inflate(R.layout.fragment_noti_second_nested, container, false);         return view;     } }        

Step 6: Creating NotiNestedFragment

Make a new fragment named NotiNestedFragment.

Paste below source code in fragment_noti_nested.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="com.exampledemo.parsaniahardik.drawerfragmentdemonuts.NotiNestedFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:gravity="center"         android:textSize="25sp"         android:textColor="#fff"         android:background="#4244d6"         android:id="@+id/tv"         android:text="Notification Nested Fragment" /> </FrameLayout>        

Put following inNotiNestedFragment.java

import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  public class NotiNestedFragment extends Fragment {      private View view;     private TextView textView;      public NotiNestedFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);      }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment         view = inflater.inflate(R.layout.fragment_noti_nested, container, false);          textView = (TextView) view.findViewById(R.id.tv);          textView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 addFragment(new NotiSecondNestedFragment(),"SecondNoti");             }         });          return view;     }      public void addFragment(Fragment fragment, String tag) {         FragmentManager manager = getActivity().getSupportFragmentManager();         FragmentTransaction ft = manager.beginTransaction();         ft.addToBackStack(tag);         ft.replace(R.id.container_body, fragment, tag);         ft.commitAllowingStateLoss();     } }

Step 7: Updating NotificationFragment

Update fragment_notification.xml as per below

<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="com.exampledemo.parsaniahardik.drawerbasicdemonuts.NotificationFragment">      <!-- TODO: Update blank fragment layout -->     <TextView         android:layout_width="match_parent"         android:layout_height="match_parent"         android:id="@+id/tv"         android:gravity="center"         android:textSize="30sp"         android:background="@color/colorAccent"         android:textColor="#fff"         android:text="Notification" />  </FrameLayout>

Update NotificationFragment.javaas following code

import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;  public class NotificationFragment extends Fragment {      private TextView textView;     private View view;      public NotificationFragment() {         // Required empty public constructor     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         // Inflate the layout for this fragment          view = inflater.inflate(R.layout.fragment_notification, container, false);          textView = (TextView) view.findViewById(R.id.tv);          textView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 addFragment(new NotiNestedFragment(), "NotiNested");             }         });         return view;     }      public void addFragment(Fragment fragment, String tag) {         FragmentManager manager = getActivity().getSupportFragmentManager();         FragmentTransaction ft = manager.beginTransaction();         ft.addToBackStack(tag);         ft.replace(R.id.container_body, fragment, tag);         ft.commitAllowingStateLoss();     } }

Now run your project, and it should work like shown in the output video.

V-navigation-drawer With V-app-bar

Source: https://demonuts.com/android-navigation-drawer/

0 Response to "V-navigation-drawer With V-app-bar"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel