ConstraintLayout 实现多个控件居中显示

本文介绍如何在ConstraintLayout中实现多个控件的居中显示,无需使用父布局嵌套。通过具体代码实例,展示了如何利用chain属性的packed模式打包元素,使控件在水平或垂直方向紧密排列。

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

目标:在不用父布局嵌套的情况下,在ConstraintLayout 包裹下直接实现多个控件(捆绑)控件居中显示

在 ConstraintLayout 1.1.3上,先用代码实现,后有实现思路

<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"
    android:background="@color/white"
    tools:context=".ui.ConstrainLayoutActivity">


    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintRight_toLeftOf="@+id/tv"
        />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="哈哈哈哈"
        android:textColor="@color/white"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@color/square_five"

        app:layout_constraintLeft_toRightOf="@id/imageView"
        />

</android.support.constraint.ConstraintLayout>

实现效果

 

实现思路是在链头加上 类似代码,让脑袋中抽象的链条 用constraintLayout的chain属性实现

       app:layout_constraintHorizontal_chainStyle="packed"

chain 除了链条方向有横向和竖向区分外, chain链条上的模式有 3种

   * spread - 元素将被展开(默认样式) 。加权链 - 在spread模式下,如果某些小部件设置为MATCH_CONSTRAINT,则它们将拆分可用空间 
   * spread_inside - 类似,但链的端点将不会扩展 
   * packed - 链的元素将被打包在一起。 孩子的水平或垂直偏差属性将影响包装元素的定位

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值