我正在尝试使用滚动背景创建一个RecyclerView,如下图所示。
这个想法是,当我向上/向下滚动查看器时,背景(浅绿色)图像也应该同步向上/向下移动。关于如何实现这一目标的任何线索?
这是我的基本RecyclerView配置
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/item_margin"
android:clipToPadding="false"
android:background="@drawable/ic_light_green_image"/>
最佳答案
我有same use-case -像Google Play音乐一样,沿着Z轴滚动位于应用栏上方的卡片列表。它实际上非常简单,但是 RecyclerView#computeVerticalScrollOffset()
的文档完全令人误解。它不计算滚动条拇指的偏移量,而是计算RecyclerView
本身滚动了多少(这正是我们在这里所需要的)。
mPostList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int scrollY = mPostList.computeVerticalScrollOffset();
// mAppBarBg corresponds to your light green background view
mAppBarBg.setTranslationY(-scrollY);
// I also have a drop shadow on the Toolbar, this removes the
// shadow when the list is scrolled to the top
mToolbarCard.setCardElevation(scrollY <= 0 ? 0 : toolbarElevation);
}
});
我的布局看起来像这样,如果有帮助的话:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- this corresponds to your light green background -->
<FrameLayout
android:id="@+id/app_bar_bg"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_container_height"
android:background="@color/primary" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- CardView adds a drop shadow to the Toolbar -->
<android.support.v7.widget.CardView
android:id="@+id/toolbar_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="0dp">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
android:id="@+id/post_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical" />
</LinearLayout>
</FrameLayout>
希望这可以帮助!