To do this, you should not start a new activity when you click an item in the navigation drawer. What you should do is work with fragments in MainActivity and replace that fragment when an item is selected instead of starting a new activity.
In your activity_main.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/tool_bar" />
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="@style/NavigationDrawerStyle"
app:menu="@menu/drawer">
</android.support.design.widget.NavigationView>
In your MainActivity
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with right fragment;
case R.id.start:
if (startfragment == null) {
startfragment = new StartFragment();
}
fragmentTransaction.replace(R.id.frame, startfragment);
fragmentTransaction.commit();
return true;
case R.id.second:
if (secondfragment == null) {
secondfragment = new Secondfragment();
}
fragmentTransaction.replace(R.id.frame, secondfragment);
fragmentTransaction.commit();
return true;
default:
if (startfragment == null) {
startfragment = new StartFragment();
}
fragmentTransaction.replace(R.id.frame, startfragment);
fragmentTransaction.commit();
return true;
}
}
});
And the template of a fragment
public class StartFragment extends Fragment {
// Ui Elements
//Atributtes
private View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_start, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}}