Android中Fragment内GridView覆盖Toolbar问题求助
解决Fragment中GridView覆盖Toolbar的问题
嘿,我太懂你这糟心的情况了——Fragment里的GridView直接把Toolbar给盖住,好好的布局全乱了。其实问题根源很简单:你用的FrameLayout是层级堆叠布局,后添加的View会覆盖前面的,要是Toolbar和GridView都直接塞在FrameLayout里,GridView自然就跑到Toolbar上头了。
下面给你两个稳当的解决办法,选哪个都能搞定:
方案一:改用LinearLayout(垂直布局)
把根布局换成垂直方向的LinearLayout,让Toolbar和GridView按上下顺序排列,GridView自动占满剩余空间。修改后的XML示例如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/reminders_Fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- Toolbar 固定在顶部 --> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:title="你的页面标题" /> <!-- GridView 占满Toolbar下方的所有空间 --> <GridView android:id="@+id/grid_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:numColumns="2" tools:listitem="@layout/your_grid_item_layout" /> </LinearLayout>
这里的关键是给GridView设置android:layout_height="0dp"和android:layout_weight="1",这样它会自动填充Toolbar下方的剩余空间,绝对不会往上跑覆盖Toolbar。
方案二:使用ConstraintLayout(更灵活)
如果之后需要更复杂的布局调整,用ConstraintLayout会更顺手——通过约束GridView的顶部到Toolbar的底部,就能彻底避免覆盖问题:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/reminders_Fragment" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- Toolbar 固定在父布局顶部 --> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:title="你的页面标题" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> <!-- GridView 被约束在Toolbar下方,占满剩余空间 --> <GridView android:id="@+id/grid_view" android:layout_width="match_parent" android:layout_height="0dp" android:numColumns="2" app:layout_constraintTop_toBottomOf="@id/toolbar" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" tools:listitem="@layout/your_grid_item_layout" /> </androidx.constraintlayout.widget.ConstraintLayout>
这个方案里,GridView的顶部被牢牢钉在Toolbar的底部,底部贴紧父布局,完全不会有越界覆盖的情况。
额外小提醒
- 千万别给GridView设置
android:layout_height="match_parent",不然它会从父布局最顶部开始布局,直接把Toolbar压在下面。 - 如果你的Toolbar是在Activity里而非Fragment内,那记得给Fragment的根布局加
android:layout_marginTop="?attr/actionBarSize",不过看你的描述Toolbar就在Fragment里,前面的方案完全够用啦。
内容的提问来源于stack exchange,提问作者Nikson
相关产品推荐
相关产品推荐

