如何在NestedScrollView+ConstraintLayout中消除TextView与EditText的多余间距
异常间距出现的原因
你提供的布局存在多处约束冲突和属性错误,是导致多余空白的核心原因:
tv_email_address存在重复的顶部约束:同时定义了app:layout_constraintTop_toBottomOf="@+id/white_line"和app:layout_constraintTop_toTopOf="@+id/tv_create_account_header"两个冲突的顶部约束,ConstraintLayout处理冲突时会强制将控件放在两个约束的中间位置,导致位置偏移。tv_create_account_header定义了app:layout_constraintBottom_toBottomOf="@+id/tv_email_address"约束,要求自身底部和邮箱标签的底部对齐,同时该控件自身设置了android:layout_marginBottom="60dp",会强制把邮箱标签向上拉扯,进一步撑开和下方输入框的间距。et_email_address定义了app:layout_constraintBottom_toTopOf="@id/iv_email_exists"约束,但你提供的布局中不存在id为iv_email_exists的控件,缺失的约束会导致输入框的位置计算异常。- NestedScrollView的直接子控件ConstraintLayout使用了
android:layout_height="match_parent",会强制子布局撑满滚动容器的高度,控件会被分散排列,自然产生额外空白。 tv_email_address自身设置了android:paddingTop="30dp"、android:paddingBottom="10dp",这两个内边距也会在控件上下增加内置空白。
修复方案
按顺序修改以下属性即可消除多余间距:
- 清理
tv_create_account_header的冲突约束,删除app:layout_constraintBottom_toBottomOf="@+id/tv_email_address"属性,不需要让头部标题和邮箱标签底部对齐。 - 清理
tv_email_address的重复顶部约束,删除app:layout_constraintTop_toTopOf="@+id/tv_create_account_header"属性,仅保留app:layout_constraintTop_toBottomOf="@+id/white_line"作为顶部约束。 - 修复输入框的缺失约束:暂时删除
et_email_address的app:layout_constraintBottom_toTopOf="@id/iv_email_exists"属性,后续需要用到对应图标时再补充控件定义即可。 - 修改ConstraintLayout的高度属性,将
android:layout_height="match_parent"改为android:layout_height="wrap_content",NestedScrollView的子控件不需要撑满滚动视口高度,使用wrap_content才能让控件按约束紧密排列。 - 若调整后仍觉得间距不符合预期,可以按需减小
tv_email_address的paddingTop和paddingBottom数值。
内容的提问来源于stack exchange,提问作者Szabolcs Nagy
相关产品推荐
相关产品推荐

