添加抽屉导航
Android Material风格的应用(一)–AppBar TabLayout
Android Material风格的应用(二)–RecyclerView
Android Material风格的应用(三)–DrawerLayout
Android Material风格的应用(四)–FloatActionButton
Android Material风格的应用(五)–CollapsingToolbar
工程源码
* 创建导航菜单
res/menu/menu-natigation.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:icon="@drawable/ic_home_black_24dp"
android:tint="@color/button_grey"
android:title="One" />
<item android:icon="@drawable/ic_favorite_black_24dp"
android:tint="@color/button_grey"
android:title="Two"/>
<item android:icon="@drawable/ic_bookmark_border_black_24dp"
android:tint="@color/button_grey"
android:title="Three"/>
</group>
</menu>
创建导航的布局 res/layout/navigation.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="@dimen/navheader_height"
android:background="?attr/colorPrimaryDark"
android:padding="@dimen/md_keylines">
</LinearLayout>
在activity_main.xml
中加入DrawerLayout
,是DrawerLayout
作为对顶层,使CoordinatorLayout
作为它的
子级
<android.support.v4.widget.DrawerLayout
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">
......
</android.support.v4.widget.DrawerLayout>
和CoordinatorLayout
的同一级添加NavigationView
<android.support.design.widget.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.java
onCreate中添加相关的逻辑
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);
}