Android开发 - AppBarLayout的使用

内容同步于我的博客:https://blog.bigrats.net/archives/android-dev-appbarlayout.html

AppBarLayout常与CollapsingToolbarLayout以及Toolbar一起使用,这三个View其实都是用以替换我们以往常用的ActionBar的。相较于ActionBar,Toolbar能够实现更加自由丰富酷炫的效果,例如随Scroll隐藏等。

Toolbar

Toolbar的主要作用即替换ActionBar的功能,自然也就能完成ActionBar所能完成的所有效果。使用Toolbar时需隐藏ActionBar,在style.xml文件中的AppTheme标签中加入以下代码:

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

或者也可以选择将AppTheme设置为.NoActionBar来取消ActionBar。(在最新版的Android Studio中,已默认采用Toolbar替代ActionBar)
然后将Toolbar放入布局文件中:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay"/>

与ActionBar不同的是,我们可以自定义Toolbar的位置和行为。下面引入的AppBarLayout与Toolbar结合能够做出更好的效果。

AppBarLayout

当某个ScrollView发生滚动时,可以通过AppBarLayout定制你的Toolbar的行为,例如跟随滚动、隐藏等。代码如下:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/id_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll" />
</android.support.design.widget.AppBarLayout>

其中app:layout_scrollFlags有四种取值:

  • scroll:跟随View的滚动事件一起滚动
  • enterAlways:当ScrollView向下移动时则向下滚动,不关心ScrollView是否滚动
  • exitUntilCollapsed:向上滑动时,首先是ScrollView跟随Toolbar向上滑动,直到Toolbar达到最小宽度ScrollView开始滚动。
  • enterAlwaysCollapsed:向下滑动时,首先是enterAlways效果,当ScrollView的高度达到最小高度时,Toolbar停止滑动,直到ScrollView不再滑动时,Toolbar继续滑动直到结束。

此时Toolbar还不能与ScrollView一起滑动,我们还需要将它们关联起来。在CoordinateLayout中我们可以自定义behavior以达到此效果,但是较为麻烦,好在Android已内置此函数,我们可以直接调用即可:

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <!-- Your Code Here -->

</android.support.v4.widget.NestedScrollView>

暂时就记录这么多了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,249评论 25 709
  • 后来,我总算学会了如何去爱可惜你早已远去消失在人海。有多少人真的是在后来才学会了爱,可是那人却已经走远…...
    我叫林小小阅读 3,783评论 0 0
  • 每天上班闲时间也多,不如在空闲的时间写写文字吧!还能提升一下自己 写这些文字的时候我应该刚刚经历了一场成...
    a2fe3d8f488b阅读 1,328评论 0 1
  • 我们在最没有能力的时候总想干一些了不起的事,来证明我们的了不起……
    沐沐木sing阅读 1,486评论 0 0

友情链接更多精彩内容