目标是实现 ToolBar 的替换,它看起来更像“SearchView”,例如:在 Google Play 应用程序中进行搜索。当 ViewPager 中的 RecyclerView 向下滚动时,此 View 也应该做出相应的 react (滑开),并在用户向上滚动列表时滑入。
这是屏幕截图:
基本上, View 本身的实现一点也不复杂。
<android.support.design.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">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
app:elevation="0dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="8dp"
app:layout_scrollFlags="scroll|enterAlways">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Other boring implementation details -->
</LinearLayout>
</android.support.v7.widget.CardView>
</android.support.design.widget.AppBarLayout>
<!-- TabLayout which is used as indicator for ViewPager -->
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</android.support.design.widget.CoordinatorLayout>
好的,向下滚动之前结果看起来像这样(因为 windowBackground
设置为白色,AppBarLayout
现在看起来是透明的):
AppBarLayout 保持白色,而不是透明背景。因此,我没有像第一个屏幕截图中那样获得所需的透明背景,而是出于未知原因得到了白色。
以前有人遇到过这个问题吗?这个问题有什么干净的解决方案吗?
附注我发现了有趣的行为:如果我从 ViewPager
中删除 app:layout_behavior="@string/appbar_scrolling_view_behavior"
,AppBarLayout
将保持透明,因为它应该是即使滚动后。这意味着问题位于 ScrollViewBehavior 的某个地方,但我没有设法找到它。
最佳答案
AppBarLayout
不是白色的。您看到的是 Activity 的窗口背景。
layout_behavior="@string/appbar_scrolling_view_behavior"
的作用是影响 View 的测量和布局,具体取决于同级 AppBarLayout
。该效果的一部分是偏移 View 的垂直位置,使其始终位于 AppBarLayout 下方。这就是为什么您会看到下面的窗口背景;没有 View 占据该空间,因此除了窗口之外没有任何内容被绘制。
看来您可能不想使用appbar_scrolling_view_behavior
,而只是允许它们始终重叠(这是您之前删除该行为时注意到的)。这就提出了当 RecyclerView 滚动到顶部并且 AppBarLayout 也滚动到屏幕上时如何不覆盖内容的问题。一个快速的解决方案是将以下属性添加到 RecyclerView
中:
<!-- Padding derived from the size and margins of the CardView -->
android:paddingTop="64dp"
android:clipToPadding="false"
关于android - 透明的AppBarLayout,其中包含CardView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383774/