Android SupportLib - 在CoordinatorLayout中使用FrameLayout与AppBarLayout占据整个屏幕高度

31

我目前在使用Android design-support库中的CoordinatorLayout中的FrameLayout遇到了问题,而我是按照这个文章创建选项卡的指示进行操作的。

基本上大部分功能都正常工作,容器片段被膨胀到FrameLayout中,并且它们的选项卡片段正确地添加到ViewPager作为选项卡(需要这样做,因为我有许多片段应该重用布局)。

我正在努力解决的问题是FrameLayout(以及选项卡片段)会占用整个屏幕高度,因此会重叠ToolbarTabLayout。为了可视化问题,我创建了以下图像:

Visualized issue

具有CoordinatorLayoutToolbarTabLayout的基本布局:

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

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <include layout="@layout/toolbar" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>

用于填充到container的片段所使用的单独布局:

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

所有片段都由我的 BaseFragment 类膨胀(在另一个SO帖子中,调用 inflater.inflate(getLayoutRes(), null); 是导致相同问题的原因)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(getLayoutRes(), container, false);
}
如果我用普通的LinearLayout替换CoordinatorLayout,那么FrameLayout会按预期从AppBarLayout下方开始,但根据文档AppBarLayout的大多数功能需要直接作为CoordinatorLayout的子级。
我可以给FrameLayout添加marginTop,但我想知道是否有适当的解决方法。感谢提供任何提示!
1个回答

49

app:layout_behavior="@string/appbar_scrolling_view_behavior"属性移动到FrameLayout上——该属性需要放置在CoordinatorLayout的直接子级上。


这解决了我遇到的相同问题,谢谢,但我不知道为什么。appbar_scrolling_view_behavior 到底是做什么的呢..? - Micro
2
@MicroR - 我建议阅读 AppBarLayout.ScrollingViewBehavior 的 Javadoc 或查看 源代码 - 它会添加所需的填充以避免与 AppBarLayout 重叠,并允许 AppBarLayout 响应滚动,如果放在可滚动视图上(例如 NestedScrollViewRecyclerView)。 - ianhanniballake
@ianhanniballake 我已经使用了您的建议,但问题是我在我的TabLayout和FrameLayout之间得到了一些额外的空间。我已经应用了背景颜色来分析原因,但在UI中没有出现任何背景颜色。 - Erum
@Erum - 没有你的代码,我们无法知道你在做什么。 - ianhanniballake
1
对我来说,将 <include layout="@layout/toolbar" /> 替换为直接放置工具栏很有帮助。 - Roger Alien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接