前言
第一次用Android Studio的时候,我就注意到了一个新建项目。我们新建项目的时候不是最后会给你几个初始化好的备选项目么,有Empty Acticity,Google Map Activity… …没错,这个就是其中之一,相信大家也都见过。第一次看到它效果这么炫,我就去看源代码,完全看不懂,连布局文件除了TextView都没什么认识的。
看Google教程一段时间后,回来看这个,发现里面的东西大部分自己都在教程里看过了,今天再回头看它的代码,做个学习的记录,发现自己成长了一点。
正文
这个项目由ToolBar,Navigation Drawer导航,Snackbar组成。我们先看看项目的效果:
这三个效果分别对应上面三个内容:
好了我们来看代码分析吧:
首先看一下这个项目的资源目录:
我们看到这项目只有一个Java文件,其余是布局文件和菜单文件,也没有为不同屏幕准备备用的layout文件:
首先看看第一个布局文件,它是整个APP的主布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
APP主结构是一个DrawerLayout实现了侧边导航,未展开是第一个效果图的样子,若展开以后是第二个效果图的样子,第一个View是通过include包括进来的布局,是APP显示内容的主布局,第二个View是Drawer导航View,这里它使用的视图是NavigationView,这个组件我还没见过。。羞羞,但看他的名字就知道是导航的啦。
下面我们看include进来的布局 app_bar_main:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"