如何在ConstraintLayout中让RecyclerView位于Spinner下方且不使用margin
问题根源
- ConstraintLayout中子View使用
match_parent作为对应方向尺寸时,该方向的约束会直接失效,View会直接撑满父布局对应方向的尺寸。你给RecyclerView设置的android:layout_height="match_parent"导致顶部对齐Spinner的约束没有生效。 - 你给RecyclerView额外添加了
android:layout_marginTop="20dp"属性,即使约束生效,该属性也会让RecyclerView和Spinner之间产生20dp的间距,不符合无margin的需求。
修改方案
- 将RecyclerView的
android:layout_height属性值从match_parent改为0dp(对应ConstraintLayout的match_constraint属性,会让View高度按照上下约束自动计算) - 删除RecyclerView的
android:layout_marginTop="20dp"属性 - 同步将FastScroller的高度也改为
0dp,避免其高度不受约束导致显示异常
修改后的完整布局代码如下:
<?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:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="30dp" tools:context=".fragment.DialerFragment"> <Spinner android:id="@+id/filterSpinner" android:layout_width="match_parent" android:layout_height="20dp" android:layout_marginTop="5dp" android:layout_marginRight="10dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="SpeakableTextPresentCheck,TouchTargetSizeCheck" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerViewCallLog" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/filterSpinner" /> <com.futuremind.recyclerviewfastscroll.FastScroller android:id="@+id/fastscroll_dialer" android:layout_width="wrap_content" android:layout_height="0dp" android:orientation="vertical" app:fastscroll__bubbleColor="#5e64ce" app:fastscroll__handleColor="#8f93d1" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@id/recyclerViewCallLog" app:layout_constraintTop_toTopOf="@+id/recyclerViewCallLog" /> </androidx.constraintlayout.widget.ConstraintLayout>
内容的提问来源于stack exchange,提问作者Unknown
相关产品推荐
相关产品推荐

