public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener,OnFragmentInteractionListener{ public NavigationView navView; public DrawerLayout drawerLayout; private Toolbar toolbar; private ActionBarDrawerToggle toggle; // 矢量图兼容支持 static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); navView = (NavigationView) findViewById( R.id.nav_view ); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); toggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); toggle.syncState(); drawerLayout.addDrawerListener(toggle); getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentResumed(FragmentManager fm, Fragment f) { super.onFragmentResumed(fm, f); if(f instanceof MineFragment) { getSupportActionBar().setTitle("我的"); }else if(f instanceof GetHelpFragment){ getSupportActionBar().setTitle("提供帮助"); }else if(f instanceof HelpFragment) { getSupportActionBar().setTitle("帮助"); }else if(f instanceof SettingFragment) { getSupportActionBar().setTitle("设置"); } } }, false); //ActionBar的返回按钮监听 toggle.setToolbarNavigationClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }); navView.setNavigationItemSelectedListener( this ); initFragment(); } private void initFragment() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace( R.id.content, new MineFragment()); ft.commit(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.nav_mine://我的 switchTo(new MineFragment()); break; case R.id.nav_get_help://获得帮助 switchTo(new GetHelpFragment()); break; case R.id.nav_help://提供帮助 switchTo(new HelpFragment()); break; case R.id.nav_setting://设置 switchTo(new SettingFragment()); break; } return true; } private void switchTo(Fragment fragment) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace( R.id.content, fragment); ft.commit(); drawerLayout.closeDrawers(); } @Override public void onFragmentInteraction(Uri uri) { }}