求助:ConstraintLayout实现顶视图底按钮布局内容少时居中问题
搞定ConstraintLayout内容少时顶部视图居中的问题
嘿,我懂你遇到的这个麻烦——用ConstraintLayout做顶部内容+底部按钮的布局,内容多的时候一切正常,可内容少到2-3个的时候,顶部视图就跑到布局中间去了,对吧?这其实是布局约束没写全导致的,我来帮你解决。
问题根源在哪?
你当前的FrameLayout只设置了左右对齐父布局、底部对齐按钮顶部,还有顶部margin,但缺了最关键的一步:把它的顶部和父布局的顶部绑定。ConstraintLayout在垂直方向如果只有底部约束、没有顶部约束的话,会默认让视图在可用空间里居中,这就是内容少时它跑偏的原因。
修复后的ConstraintLayout代码
只需要给顶部的FrameLayout加一行app:layout_constraintTop_toTopOf="parent",就能让它牢牢顶在布局顶部,不管内容多少都不会乱跑:
<android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" <!-- 新增这行,把顶部钉死在父布局顶部 --> app:layout_constraintBottom_toTopOf="@id/segmentedButton"> <!-- 这里放你的内容视图 --> </FrameLayout> <Button android:id="@+id/segmentedButton" android:layout_width="match_parent" android:layout_height="50dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"> </Button> </android.support.constraint.ConstraintLayout>
顺便说下LinearLayout的正确写法
你之前试LinearLayout没解决?应该是布局属性没设对。给你个靠谱的写法:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> <!-- 你的内容视图 --> </FrameLayout> <!-- 这个占位View会占满中间所有剩余空间,把按钮挤到底部 --> <View android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> <Button android:id="@+id/segmentedButton" android:layout_width="match_parent" android:layout_height="50dp"/> </LinearLayout>
这里用权重占位的方式,让顶部内容保持自适应高度,同时强制按钮固定在底部,完全不会出现居中的问题。
内容的提问来源于stack exchange,提问作者Rustam Ibragimov
相关产品推荐
相关产品推荐

