非常容易学的android笔记4
nav drawer菜单
nav_menu
新建一个menu
tools:showIn=“navigation_view”
这个就是形成右边那条缝的
主菜单activity_main.xml
这个 NavigationView 里面包了两个
app:headerLayout="@layout/main_navigate"
app:menu="@menu/nav_menu"
main_navigate
需要几个fragment,就是导航过去的界面,上个教程有。
再说下3个点的这些图标问题,其实不需要放,只需要设置menu就可以,但是有时候menu是假的,才需要放图标
这里就是一旦设置好menu,这里几个点就自己出现了。
MainActivity.class
注入 drawerLayer , navigationView, toolbar;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayer;
NavigationView navigationView;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
划掉这个,不然会出错
This Activity already has an action bar supplied by the window decor. Do not request Window.>FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
很多人会在主菜单中把action bar给设为 false,如果自定义的话,我这边比较简单,所以就自带了,这一行就不能出现了
// setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayer, toolbar, R.string.open_nav, R.string.close_nav);
drawerLayer.addDrawerListener(toggle);
toggle.syncState();
接下来是导航
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
break;
case R.id.nav_gallery:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_gallery()).commit();
break;
case R.id.nav_slideshow:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_slideshow()).commit();
break;
}
drawerLayer.closeDrawer(GravityCompat.START);
return true;
}
});
if (savedInstanceState != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
navigationView.setCheckedItem(R.id.nav_home);
}
- 用户点击 Back 键时系统调用的方法
public void onBackPressed() {
if (drawerLayer.isDrawerOpen(GravityCompat.START)) {
drawerLayer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
好了