Android Constraint Layout:如何让View占据屏幕上半部分
嘿,我来帮你揪出问题所在~
你现在的代码有两个关键错误,导致TextView没法占满屏幕上半部分:
给父ConstraintLayout设置了多余的权重属性
app:layout_constraintVertical_weight这个属性是给ConstraintLayout内部的子控件用的,用来在垂直链中分配剩余空间,父布局本身完全不需要这个属性,你给它加app:layout_constraintVertical_weight="2"完全是画蛇添足。TextView的垂直约束不完整
你只给TextView设置了顶部和左右的约束,但没有设置底部约束,这就导致垂直方向的约束链没形成,权重属性根本起不了作用,所以TextView只会显示自身内容的高度,而不是你期望的占上半部分。
下面给你两种靠谱的实现方式,选一种就行:
方法一:用水平参考线(最直观)
添加一条水平方向的参考线,把它放在屏幕50%高度的位置,然后把TextView的底部约束到这条线的顶部,这样TextView就刚好占满上半部分:
<?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=".MainActivity"> <!-- 水平参考线,位于屏幕垂直中线(50%高度) --> <android.support.constraint.Guideline android:id="@+id/horizontal_mid_guideline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.5"/> <TextView android:text="Test" android:background="@color/colorPrimaryDark" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/horizontal_mid_guideline"/> </android.support.constraint.ConstraintLayout>
方法二:用垂直链+权重
如果想用权重机制实现,需要让TextView和一个空白View形成垂直链,两个控件的高度都设为0dp,权重都设为1,这样它们会平分屏幕垂直空间:
<?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=".MainActivity"> <TextView android:text="Test" android:background="@color/colorPrimaryDark" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/blank_view" app:layout_constraintVertical_weight="1"/> <!-- 空白View,用来占据下半部分空间 --> <View android:id="@+id/blank_view" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/textView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_weight="1"/> </android.support.constraint.ConstraintLayout>
内容的提问来源于stack exchange,提问作者Foobar
相关产品推荐
相关产品推荐

