使用ConstraintLayout时ListView与Toolbar重叠问题
解决ConstraintLayout中Toolbar与ListView重叠的问题
刚好我之前也碰到过类似的情况,其实只要给ListView加上正确的约束就能搞定!你的需求很清晰:Toolbar固定在顶部,ListView占满剩下的全部空间,下面是调整后的完整布局代码:
<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="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/toolbar" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </android.support.constraint.ConstraintLayout>
关键的几个点给你划重点:
- Toolbar的约束:通过
app:layout_constraintTop_toTopOf="parent"把它钉在布局顶部,左右也和父布局对齐,高度用wrap_content就好,不用硬写固定值。 - ListView的核心调整:
- 把高度设为
0dp(也就是match_constraint),这样它会根据约束自动填充剩余空间; - 用
app:layout_constraintTop_toBottomOf="@id/toolbar"让ListView的顶部紧贴Toolbar的底部,从根源上避免重叠; - 同时把左右和底部都和父布局对齐,确保它能占满剩下的所有区域。
- 把高度设为
之前的布局之所以重叠,大概率是因为ListView没有设置顶部和Toolbar底部的约束,或者高度没设成0dp,导致它从布局顶部开始绘制,就和Toolbar叠在一起啦。
内容的提问来源于stack exchange,提问作者Hilikus
相关产品推荐
相关产品推荐

