我有一个 CoordinatorLayout
,在 AppBarLayout
中有一个 Toolbar
和一个 TabLayout
。此外,我在 CoordinatorLayout
内但在 ViewPager
外有一个 ViewPager
。
问题是 ViewPager 的
高度比实际可用的高度大,导致我的 Fragment
中的某些 View 被剪切。
<?xml version="1.0" encoding="utf-8"?>
<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:background="@color/lightGray"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:layout_scrollFlags="scroll|enterAlways"/>
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:scrollbars="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="false"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
最佳答案
更新:我不再推荐这个了。我发现它导致无限循环调用 onDependentViewChanged
。
根据上面 Yevhenii 的回答,我想我设法以更简单的方式解决了这个问题:
class KeepWithinParentBoundsScrollingBehavior : AppBarLayout.ScrollingViewBehavior {
constructor() : super()
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
if (dependency !is AppBarLayout) {
return super.onDependentViewChanged(parent, child, dependency)
}
val layoutParams = child.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.height = parent.height - dependency.bottom
child.layoutParams = layoutParams
return super.onDependentViewChanged(parent, child, dependency)
}
}
然后在 ViewPager
或 AppBar
下方的任何 View 上设置 app:layout_behavior="your.package.KeepWithinParentBoundsScrollingBehavior"
。
请注意,这不是适用于所有 CoordinatorLayout
的通用解决方案,但当您在应用栏下方有一个您不想让其超出底部的 View 时,它似乎可以工作父 CoordinatorLayout 的。
更新:
您还应该在 ViewPager 上设置 app:layout_anchor="@id/app_bar"
以应对键盘消失的情况。如果您不这样做,ViewPager
布局将不会在键盘消失时刷新并且 ViewPager
将显示为被截断。
关于android - ViewPager 在 Coordinator 布局中的高度超过可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39739882/