
/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="iterator.ir.a048.MainActivity"
android:id="@+id/drawerLayout">
<!--Content-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_container">
</FrameLayout>
</LinearLayout>
<!--Drawer-->
<android.support.design.widget.NavigationView
android:id="@+id/navigationView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// load at application start up
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
navigationView= (NavigationView) findViewById(R.id.navigationView);
drawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
// handle navigation menu item click event
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.itemHome:
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
item.setChecked(true);
drawerLayout.closeDrawers();
return true;
case R.id.itemAdd:
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new AddFragment());
fragmentTransaction.commit();
item.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
}
References
https://github.com/mhdr/AndroidSamples/tree/master/048
https://www.youtube.com/watch?v=o4gF75f4BoI&index=78&list=PLshdtb5UWjSp0879mLeCsDQN6L73XBZTk