AppBarLayout效果:
当向下滑动屏幕是时 顶部就会出现
当向上滑动屏幕时 顶部就会折叠
向下滑动时:
向上滑动后:
接下来 看代码:
Xml总布局(LinearLayout):
可以使用Design工具 找到AppBarLayout这个布局控件(第一次使用需要下载),然后将其拖入我们的总布局,拖入的时候会出现一个弹框:
这里我们选择了这三个选项,第一个是我们需要的一个Toolbar,第三个是设置我们页面里需要的几个tab,也就是需要几个碎片,案例里我们需要三个
成功将APPBarLayout拖入布局之后,代码如下(有些是我们自己添加的,我写了注释,请认真比对查看)
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways">
<!--这里面可加入你想设置的toolbar里面的样式-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="首页" />
</androidx.appcompat.widget.Toolbar>
<!-- app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:minHeight="20dp"
这两句可以设置向上滑的时候有多少高度是固定的不缩上去
-->
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"//这句是默认的
//app:layout_scrollFlags="scroll|exitUntilCollapsed"
//android:minHeight="20dp"
app:tabMode="scrollable">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text