与 AppBarLayout 重叠滚动视图

我想从 材料设计滚动技术中实现“灵活空间与重叠内容”的模式,比如在 这个视频中: Flexible Space with overlapping content GIF

我现在的 XML 布局如下:

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


<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="192dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">


<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">


<android.support.v7.widget.Toolbar
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>


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


<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<....>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

有没有一种简单的方法可以通过使用设计库来实现这一点?或者我必须建立一个自定义的 协调员布局,行为来做到这一点?

40435 次浏览

In fact, overlaying the scrolling view with the AppBarLayout is an included feature of the Android Design Support Library: you can use the app:behavior_overlapTop attribute on your NestedScrollView (or any View using ScrollingViewBehavior) to set the overlap amount:

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

Note that app:behavior_overlapTop only works on views that have the app:layout_behavior="@string/appbar_scrolling_view_behavior" as it is the Behavior that is using the attribute (not the View or the Parent ViewGroup, as attributes usually apply to), hence the behavior_ prefix.

Or set it programmatically via setOverlayTop():

NestedScrollView scrollView = ...
CoordinatorLayout.LayoutParams params =
(CoordinatorLayout.LayoutParams) scrollView.getLayoutParams();
AppBarLayout.ScrollingViewBehavior behavior =
(AppBarLayout.ScrollingViewBehavior) params.getBehavior();
behavior.setOverlayTop(128); // Note: in pixels

In addition to the accepted answer, call setTitleEnabled(false) on your CollapsingToolbarLayout to make the title stay fixed at the top as in the example.

Like this:

CollapsingToolbarLayout.setTitleEnabled(false);

or by adding it in xml like this:

app:titleEnabled="false"

Otherwise the title could disappear behind the overlapping content, unless of course, that's the behaviour you want.