Android布局设置8dp四边边距无效,顶部无间距问题求助
嘿,我来帮你搞定这个RecyclerView顶部边距消失的问题~
问题原因
你设置的android:layout_margin="8dp"其实是生效的,但因为你的布局结构是CoordinatorLayout + AppBarLayout,默认情况下下方的内容布局会从屏幕最顶端开始绘制,和AppBarLayout重叠在一起,导致RecyclerView的顶部边距被AppBar挡住了,看起来像是没有边距。
另外,你给RecyclerView加了app:layout_constraintVertical_bias="1.0",这个属性会让RecyclerView强制靠父布局底部对齐,这可能也会干扰你预期的布局效果,建议去掉它。
解决方案
1. 给内容布局添加AppBar滚动行为
找到你app_bar_main.xml里include的content_main.xml,给它的根布局加上app:layout_behavior="@string/appbar_scrolling_view_behavior"属性。这个属性会让CoordinatorLayout自动调整内容布局的位置,避开AppBarLayout的区域,这样你的RecyclerView顶部边距就能正常显示了。
修改后的content_main.xml示例(假设根布局是FrameLayout):
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- 这里是加载MainFragment的容器,比如FrameLayout或者直接放置Fragment布局 --> </FrameLayout>
2. 优化RecyclerView的约束
去掉RecyclerView上多余的app:layout_constraintVertical_bias="1.0"属性,因为你已经设置了top_toTopOf="parent"和bottom_toBottomOf="parent",足够让RecyclerView充满整个父布局了。
修改后的MainFragment布局:
<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragments.MainFragment"> <android.support.v7.widget.RecyclerView android:id="@+id/recycleViewRandom" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
效果验证
做完这两步之后,你的RecyclerView应该会在AppBarLayout下方显示,并且上下左右都有8dp的边距,和你预期的效果一致啦~
内容的提问来源于stack exchange,提问作者jackfield

