Android开发 - AppBarLayout的使用

2018-05-20  本文已影响0人  蒋佳秋

内容同步于我的博客: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有四种取值:

此时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>

暂时就记录这么多了。

上一篇 下一篇

猜你喜欢

热点阅读