约束布局ConstraintLayout的使用(一)

本文对比了RelativeLayout与ConstraintLayout在布局管理上的区别,展示了如何使用ConstraintLayout更灵活地定位UI元素,并避免常见的布局问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ConstraintLayout是一个ViewGroup,可用作支持库,您可以在从API级别9(Gingerbread)开始的Android系统上使用。

RelativeLayout 和 ConstraintLayout 有许多类似的地方。你可以相对地放置你的子视图,这第一眼看起来和 ConstraintLayout 实现的一样。但RelativeLayout 有一些你可能早就知道的问题。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="34dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"/>

</RelativeLayout>

上面的代码在容器的右下方放了一个按钮


如果把RelativeLayout的layout_height改成wrap_content,按钮就直接在容器的底部。

如果使用ConstraintLayout就可以避免这个问题

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginBottom="34dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"/>

</android.support.constraint.ConstraintLayout>

具体使用请看下一篇:
约束布局ConstraintLayout的使用(二)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值