添加抽屉导航
DrawerLayout
工程源码
创建导航菜单
res/menu/menu-natigation.xml
android:tint="@color/button_grey"
android:title="One" />
android:tint="@color/button_grey"
android:title="Two"/>
android:tint="@color/button_grey"
android:title="Three"/>
创建导航的布局 res/layout/navigation.xml
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="@dimen/navheader_height"
android:background="?attr/colorPrimaryDark"
android:padding="@dimen/md_keylines">
在activity_main.xml中加入DrawerLayout ,是DrawerLayout作为对顶层,使CoordinatorLayout作为它的
子级
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
......
和CoordinatorLayout的同一级添加NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/nav_view"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header"
app:menu="@menu/menu_navigation">
在MainActivity.javaonCreate中添加相关的逻辑
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBar supportActionBar = getSupportActionBar();
if(supportActionBar != null){
supportActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
item.setChecked(true);
mDrawerLayout.closeDrawers();;
return true;
}
});
相应左上角的menu,打开导航
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
mDrawerLayout.openDrawer(GravityCompat.START);
}
return super.onOptionsItemSelected(item);
}