一、Toolbar
ActionBar为原生的标题栏,Toolbar有着比ActionBar更灵活更丰富的样式,因此更多使用Toolbar来代替ActionBar。
指定不带ActionBar的主题
在res/values/theme.xml中设置主题为Theme.AppCompat.NoActionBar或Theme.AppCompat.Light.NoActionBar
1 | <resources xmlns:tools="http://schemas.android.com/tools"> |
设置并显示Toolbar
通过findViewById()得到Toolbar实例,之后调用setSupportActionBar()方法传入Toolbar实例。
1 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); |
修改属性android:label,指定在Toolbar中显示的文字
在Toolbar上添加一些按钮
通过创建Menu resource file,命名为toolbar.xml,在该布局文件中添加item,用来表示添加的一些按钮
1 |
|
app:showAsAction来指定按钮的显示位置,always表示永远显示在Toolbar中;ifRoom表示屏幕空间足够的情况下显示在Toolbar中;never表示永远显示在菜单中。Toolbar中的action按钮只显示图标,菜单中的action只显示文字。
1 | public boolean onCreateOptionsMenu(Menu menu) { |
二、DrawerLayout
滑动菜单就是将一些菜单选项隐藏起来,不放在主屏幕上,然后通过滑动的方式将菜单显示出来。
子控件布局
DrawerLayout允许放入两个直接子控件,第一个子控件为主屏幕显示内容,第二个子控件为滑动菜单中显示内容。
1 |
|
第二个子控件中的layout_gravity属性必须指定,left表示滑动菜单在左边,right表示滑动菜单在右边,start会根据系统语言进行判断左或是右。
点击打开隐藏菜单
首先得到DrawerLayout实例,然后调用getSupportActionBar方法得到ActionBar实例,接着调用ActionBar的setDisplayHomeAsUpEnabled让导航按钮显示出来。Toolbar最左侧的这个按钮叫做HomeAsUp按钮,其id永远都是android.R.id.home,在点击事件中调用DrawerLayout的openDrawer方法展示出滑动菜单。
1 | mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); |
三、NavigationView
用NavigaitonView对滑动菜单页面进行布局设计。设置滑动菜单隐藏界面的头部布局文件nav_header.xml以及内置菜单布局文件nav_menu.xml,并通过app:menu和app:headerLayout将这两个布局文件加载到主布局文件中。
1 |
|
菜单项点击响应事件
1 | NavigationView navView = (NavigationView) findViewById(R.id.nav_view); navView.setCheckedItem(R.id.nav_call); |
四、FloatingActionButton与Snackbar
FloatingActionButton为悬浮按钮,点击事件与普通按钮并无差别。Snackbar与Toast的相似之处在于都可以作为提示的工具,Toast的作用是告诉用户现在发生了什么,用户只能被动接收这个事情,不能让用户进行选择;Snackbar允许在提示中加入一个可交互按钮,进而可以执行一些额外操作。
1 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); |
五、CoordinateLayout
当点击悬浮按钮弹出SnackBar,此时的提示消息会挡住悬浮按钮,CoordinateLayout可以解决这个问题,CoordinateLayout可以监听其所有子控件的各种事件,自动做出最合理的响应。
六、CardView
在app/build.gradle中添加依赖implementation “androidx.cardview:cardview:1.0.0”
1 | <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="35dp" app:cardCornerRadius="4dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:id="@+id/fruit_content_text"/></androidx.cardview.widget.CardView> |
通过app:cardCornerRadius指定卡片圆角弧度;通过app:elevation指定卡片高度
七、AppBarLayout
内部有很多滚动事件的封装
八、SwipeRefreshLayout
用来设置下拉刷新,对于需要下拉刷新的控件,需要将其布局在SwipeRefreshLayout内,
1 | <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/swipe_refresh" app:layout_behavior="@string/appbar_scrolling_view_behavior"><androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recycler_view" /></androidx.swiperefreshlayout.widget.SwipeRefreshLayout> |