先看布局
DrawerLayout+NavigationView
headerLayout+menu
代码
第一步:NavigationView设置监听事件
setNavigationItemSelectedListener
第二步:DrawerLayout和toolbar整合
toolBar.inflateMenu(R.menu.toolbar_menu);
ActionBarDrawerToggledrawerToggle=newActionBarDrawerToggle(this,myDrawerlayout,toolBar,R.string.open,R.string.close);
drawerToggle.syncState();
myDrawerlayout.addDrawerListener(drawerToggle);
private voidinitDrawerLayout(){
view=myNavigationview.getHeaderView(0);
view.setOnClickListener(newView.OnClickListener(){
@Override
public voidonClick(Viewview){
Toast.makeText(MainActivity.this,"点击了header",Toast.LENGTH_SHORT).show();
}
});
myNavigationview.setNavigationItemSelectedListener(newNavigationView.OnNavigationItemSelectedListener(){
@Override
public booleanonNavigationItemSelected(@NonNullMenuItemitem){
switch(item.getItemId()){
caseR.id.menu_app_update:
Toast.makeText(MainActivity.this,"应用更新",Toast.LENGTH_SHORT).show();
break;
caseR.id.menu_message:
Toast.makeText(MainActivity.this,"消息中心",Toast.LENGTH_SHORT).show();
break;
caseR.id.menu_setting:
Toast.makeText(MainActivity.this,"设置",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
toolBar.inflateMenu(R.menu.toolbar_menu);
ActionBarDrawerToggledrawerToggle=newActionBarDrawerToggle(this,myDrawerlayout,toolBar,R.string.open,R.string.close);
drawerToggle.syncState();
myDrawerlayout.addDrawerListener(drawerToggle);
}