赞
踩
作为一名程序员,可能会经历以下难受的事情:
ConstraintLayout是Android Studio 2.3版本中推出的一种布局,它被认为是一种更加灵活、更加强大的布局,它可以在大多数情况下替代其他布局,比如RelativeLayout、LinearLayout等。下面是ConstraintLayout的使用详解。
约束(Constraint):Constraint指的是控件与父容器或其它控件之间的关系,比如:控件的上边缘与其父容器的上边缘对齐、控件的左边缘与另一个控件的右边缘对齐等。
约束线(Constraint Line):Constraint Line指的是两个控件之间的连接线,每个控件都有四条Constraint Line,分别是上、下、左、右。
在使用ConstraintLayout布局时,需要做的第一件事情就是在build.gradle文件中添加依赖:
- dependencies {
- implementation 'com.android.support.constraint:constraint-layout:2.0.4'
- }
然后,在layout文件中使用ConstraintLayout标签:
- <androidx.constraintlayout.widget.ConstraintLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <!-- 子控件 -->
- </androidx.constraintlayout.widget.ConstraintLayout>
接下来,我们就可以开始使用约束来布局了。下面是ConstraintLayout的典型布局方式:
- <Button
- android:id="@+id/btn1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 1" />
-
- <Button
- android:id="@+id/btn2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 2" />
-
- <Button
- android:id="@+id/btn3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 3" />
-
- <Button
- android:id="@+id/btn4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 4" />
-
- <Button
- android:id="@+id/btn5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 5" />
-
- <Button
- android:id="@+id/btn6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 6" />
-
- <Button
- android:id="@+id/btn7"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 7" />
-
- <Button
- android:id="@+id/btn8"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 8" />
-
- <Button
- android:id="@+id/btn9"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 9" />
-
- <Button
- android:id="@+id/btn10"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button 10" />
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
效果图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。