今日看点Android 技术开发Android开发

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

2016-11-14  本文已影响0人  CoderMiner

添加抽屉导航

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

DrawerLayout
工程源码
<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);
}
上一篇下一篇

猜你喜欢

热点阅读