本文根据本人学习和使用记录的内容。
ConstraintLayout,比较牛逼的一种布局,结合了其他几种布局的优点,也可以看做RelativeLayout的升级版。
使用ConstraintLayout需要引入:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
首先很重要也是很基础的几个属性
app:layout_constraintTop_toTopOf="@id/id2"
app:layout_constraintTop_toBottomOf="@id/id2"
app:layout_constraintLeft_toLeftOf="@id/id2"
app:layout_constraintLeft_toRightOf="@id/id2"
app:layout_constraintRight_toLeftOf="@id/id2"
app:layout_constraintRight_toRightOf="@id/id2"
app:layout_constraintBottom_toTopOf="@id/id2"
app:layout_constraintBottom_toBottomOf="@id/id2"
这几个属性可以这样理解:
以layout_constraintTop_toTopOf="@id/id2"为例,此view的top和id2的view的top对齐。
当然也可以设值为parent(layout_constraintTop_toTopOf=“parent”),意思是与父容器的top对齐。
example:
textview只设置了 app:layout_constraintTop_toTopOf=“parent”。
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"
android:text="hello world"/>
效果是与父view的top对齐,那效果就和默认的对齐方式一致。
再设置 app:layout_constraintBottom_toBottomOf="parent"底部与父view的bottom对齐
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="hello world"/>
再设置:
app:layout_constraintTop_toTopOf=“parent”
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent”
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/holo_green_light"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="hello world"/>