You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让mRecyclerView填充ConstraintLayout中广告与Toolbar间的剩余空间?

如何用ConstraintLayout实现顶部广告+中间RecyclerView+底部Toolbar的布局

嘿,我来帮你搞定这个布局问题!要实现顶部Google广告、底部Toolbar,中间mRecyclerView填充剩余所有空间的效果,核心是给每个控件设置正确的约束关系,同时把RecyclerView的宽高改成0dp(也就是match_constraint),让它根据上下控件的约束自动填充剩余空间。

完整的布局代码示例

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 顶部Google广告控件,这里以AdView为例,你可以替换成实际的广告控件 -->
    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:adSize="BANNER"
        app:adUnitId="@string/ad_unit_id"/>

    <!-- 中间的RecyclerView,填充广告和Toolbar之间的所有空间 -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/mRecyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/adView"
        app:layout_constraintBottom_toTopOf="@id/toolbar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <!-- 底部Toolbar -->
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarHeight"
        android:background="?attr/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

关键要点解释

  • 广告控件:设置layout_height="wrap_content"(或广告要求的固定高度),顶部、左右都和父布局对齐,确保它贴在页面最上方。
  • RecyclerView:
    • 把原来硬编码的layout_width和layout_height改成0dp,这是ConstraintLayout里的特殊值,表示“根据约束来匹配空间”。
    • 顶部约束到广告控件的底部,底部约束到Toolbar的顶部,左右和父布局对齐,这样它就会自动填充广告和Toolbar之间的所有剩余空间。
  • Toolbar:高度用系统默认的?attr/actionBarHeight,底部和父布局对齐,左右也和父布局对齐,固定在页面最下方。

针对你提到的Code B问题

Android Studio拖放控件时自动生成的硬编码宽高(比如layout_width="300dp"、layout_height="400dp")是不符合需求的,直接替换成上面的0dp和对应的约束就能解决问题啦。

内容的提问来源于stack exchange,提问作者HelloCW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:11:51