Android Material风格的应用(三)--DrawerLayout

泄露秘密 提交于 2019-11-28 22:08:34

添加抽屉导航

Android Material风格的应用(一)--AppBar TabLayout
Android Material风格的应用(二)--RecyclerView
Android Material风格的应用(三)--DrawerLayout
Android Material风格的应用(四)--FloatActionButton
Android Material风格的应用(五)--CollapsingToolbar

DrawerLayout工程源码

  • 创建导航菜单 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.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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!