Android的ConstraintLayout布局控件堆积一起的解决方法

Android的ConstraintLayout布局控件堆积的解决

ConstraintLayout作为一款可以灵活调整view位置和大小的Viewgroup被Google推荐,以前创建布局,默认根元素都是LinearLayout,现在是ConstraintLayout了。ConstraintLayout能够以支持库的形式最小支持到API 9,同时也在不断的丰富ConstraintLayout的API和功能。ConstraintLayout在复杂布局中能够有效的,降低布局的层级,提高性能,使用更加灵活。好处很多
但是在Android studio种新建的布局文件往往默认为ConstraintLayout布局,而不是LinearLayout线性布局。在初次使用xml中,对布局属性的不熟悉会导致布局中的控件全部堆积在一起。
我在开始学习Android的时候,刚开始也遇到了控件都堆积在一起的问题,放置的button控件,edittext,图片等都堆在最上。
在这里插入图片描述
视图模式可以对控件进行排布和拖拽,但是如果布局复杂,控件过多就很麻烦,最后查看了谷歌相关的文件,可以直接在代码里进行属性的改变,通过简单的使用ConstraintLayout的属性就可以实现。

在每个控件下添加 app:layout_constraintTop_toBottomOf="@id/button"
@后是引用。

<TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="TextView"
        android:textSize="24sp"
        android:textColor="#00ff00"
        tools:ignore="MissingConstraints" />
    <Button
        android:id="@+id/button"
        app:layout_constraintTop_toBottomOf="@id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:ignore="MissingConstraints" />
     <EditText
         android:id="@+id/edit_text"
         app:layout_constraintTop_toBottomOf="@id/button"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:hint="please type sth here"
         android:maxLines="2"
         tools:ignore="MissingConstraints" />
       <ImageView
           android:id="@+id/image_view"
           app:layout_constraintTop_toBottomOf="@id/edit_text"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/img_1"
           tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

以相对位置属性layout_constraintLeft_toRightOf来说,constraintLeft表示控件本身的左边,一个控件框有四条边,因此它的的上、右、下边分别对应着constraintTop、constraintRight、constraintBottom。toRightOf则表示位于另外一个控件的右边,因此对应还有toLeftOf、toRghtOf、toBottomOf,分别位于控件的左、右、下边。总结的说,constraintXXX表示View自身约束的边,toXXXOf表示另一个View的边,而XXX的值可以是Left、Top、Right、Bottom,分别对应左,上、右、下边。layout_constraintStart_toEndOf也是类似的道理。另外需要注意的是,view的位置可以相对于同层的view和parent,在相对于parent的时候toLeftOf、toTopOf、toRghtOf、toBottomOf分别表示位于parent的内部左上右下边缘。

效果如下:
在这里插入图片描述
此时想要两个控件中间对齐怎么办?ConstraintLayout提供了layout_constraintBaseline_toBaselineOf属性。

代码里添加app:layout_constraintBaseline_toBaselineOf="@id/××"

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值