目錄
前言
前些天看了很多app都有toolbar隨滑動隱藏或顯示,比如酷安。
效果挺棒的,想到了我之前的ListView Demo ,添加一個這樣的toolbar會是什么效果呢? 【之前的Demo_ListView】
為了增加點東西,在listview的基礎上嵌套一個PagerView在外部。
實現
開始來添加toolbar,AppBar包裹的toolbar,這里用的包是androidx,如果你想用support,應使用android.support.v7.widget.Toolbar 和 android.support.design.widget.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="?attr/colorPrimary"
android:minHeight="40dp"
app:layout_scrollFlags="scroll|enterAlways"
app:maxButtonHeight="25dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/nscroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.viewpager.widget.ViewPager
android:id="@+id/activityViewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" />
</androidx.core.widget.NestedScrollView>
<include layout="@layout/ite_tool_bar" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
遇到的問題和解決辦法
NestedScrollView下的ViewPager視圖被壓縮不顯示
NestedScrollView 設置
android:fillViewport="true"
ViewPager上部分被Toolba遮擋
NestedScrollView 設置了
app:layout_behavior="@string/appbar_scrolling_view_behavior"
toolbar就不會把ViewPager遮擋住。
修改好main_activity.xml之后效果是這樣的:
NestedScrollView與ListView滑動沖突

完成后效果:
其他問題
去掉toolbar陰影
AppBarLayout加個屬性 app:elevation = "0dp" android:elevation 不行,因為他是兼容庫的
toolbar延伸到狀態欄
在style.xml 中設置
禁用NestedScrollview滾動
在使用RecvclerView的快速滾動條時,發現他與NestedScrollView的滑動沖突,會阻斷快速滑動條的滑動事件,在網上查找了解決辦法,最終在文章【禁用NestedScrollview滾動】,找到,感謝作者。
在解決問題時閱讀到的相關優秀文章
Material Design系列教程(5) - NestedScrollView
Android CoordinatorLayout實戰案例學習《一》