How to use the Android navigation drawer template and go to different fragments by clicking the items of the navigation drawer menu?
Step By Step
Open Android Studio.Create A New Project.
Select Android Navigation Drawer Template.
Open app_bar_main.xml
Replace <include layout="@layout/content_main" />
with FrameLayout
Add Fragments to the project.
- Uncheck Include fragment factory methods?
- Uncheck Include interface callbacks?
Make sure to use android.support.v4.app.Fragment in the fragment class.
- import android.support.v4.app.Fragment;
Customize the fragment xml layout.
Implement MainActivity.java
Declare NavigationView and Toolbar.
- private NavigationView navigationView=null;
- private Toolbar toolbar=null;
Set the default Fragment within onCreate method.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Set the default Fragment MainFragment mainFragment=new MainFragment(); FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container,mainFragment); fragmentTransaction.commit(); }
In the method onNavigationItemSelected implement different FragmentTransaction.
if (id == R.id.nav_main) { MainFragment mainFragment=new MainFragment(); FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container,mainFragment); fragmentTransaction.commit(); } else if (id == R.id.nav_area) { AreaFragment areaFragment=new AreaFragment(); FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container,areaFragment); fragmentTransaction.commit(); }
Android Tutorial 9 - The Navigation Drawer
0 留言