Android Kotlin开发:ConstraintLayout中Fragment容器无法填充指定空间求助
解决Fragment容器无法填充Toolbar与底部导航间空间的问题
嘿,这个问题我之前也碰到过!你的Fragment容器没法占满中间区域的核心原因是你给它设置了wrap_content的高度——这会让它只适配内部内容的高度,而不是利用ConstraintLayout的约束来填充可用空间。
只需要做一个关键修改就能解决:
修改步骤
- 将
fragment_container的android:layout_height从wrap_content改为0dp:在ConstraintLayout中,0dp对应的是「匹配约束(match_constraint)」,它会根据你设置的top_toBottomOf="@id/toolbar"和bottom_toTopOf="@id/bottom_navigation_view"这两个约束,自动填充Toolbar和底部导航之间的所有垂直空间。 - (可选优化)把BottomNavigationView的
layout_constraintLeft/layout_constraintRight换成layout_constraintStart/layout_constraintEnd,这样能更好地支持从右到左的布局规范。
修改后的完整XML代码
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textColor="@android:color/white" android:textSize="@dimen/toolbar_title_text_size" android:textStyle="bold" /> </android.support.v7.widget.Toolbar> <FrameLayout android:id="@+id/fragment_container" android:layout_width="0dp" android:layout_height="0dp" <!-- 这里改成0dp --> android:background="@color/colorAccent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/toolbar" app:layout_constraintBottom_toTopOf="@id/bottom_navigation_view"/> <android.support.design.widget.BottomNavigationView android:id="@+id/bottom_navigation_view" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" <!-- 换成Start/End --> app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:menu="@menu/menu_main" /> </android.support.constraint.ConstraintLayout>
这样修改之后,你的Fragment容器就会完美填充Toolbar和底部导航之间的所有空间啦!
内容的提问来源于stack exchange,提问作者isuPatches
相关产品推荐
相关产品推荐

