ConstraintLayout 流式布局:Flow的动态加载

废话不多说,直接上菜,内容也比较简单。

首先,第一部分:布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/constraintLayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

  <androidx.constraintlayout.helper.widget.Flow
      android:id="@+id/flow"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      app:flow_wrapMode="chain"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      />
</androidx.constraintlayout.widget.ConstraintLayout>

Flow的部分属性含义:

<androidx.constraintlayout.helper.widget.Flow
    android:id="@+id/flow"
    //宽度要指定,否则会顶出屏幕外面
    android:layout_width="0dp" 
    android:layout_height="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginEnd="10dp"
    //引用的id(内部的view的id)
    app:constraint_referenced_ids="tv_type,tv_online_state,tv_switch_state"
    //chain或者aligned,chain:链形式,依次挨着排,aligned会两端对齐
    app:flow_wrapMode="chain" 
    //首行的对齐方式,packed:靠最左侧挨着排,水平间隔:horizontalGap生效, 
    // spread:分散对齐,两端不贴边。spread_inside:分散对齐,两头贴边
    app:flow_firstHorizontalStyle="packed"
    //最后一行的对齐方式,其他属性参考firstHorizontalStyle
    app:flow_lastHorizontalStyle="packed"
    // 全局水平bias,为0时,每行都贴左边,可解决中间行单独占一行时,不贴最左侧的问题
    app:flow_horizontalBias="0"
    // 第一行水平bias,为0时,贴最左边
    app:flow_firstHorizontalBias="0"
    // 最后一行水平bias,为0时,贴最左边
    app:flow_lastHorizontalBias="0"
    // 控件水平方向上的间隔
    app:flow_horizontalGap="10dp"
    // 行间隔
    app:flow_verticalGap="8dp"
    app:layout_constraintEnd_toStartOf="@id/ibt_go"
    app:layout_constraintStart_toEndOf="@id/guideline"
    app:layout_constraintTop_toTopOf="@id/tv_org_name" />

第二部分,代码的方式,动态添加

val ids = mutableListOf<Int>()
for (i in 0..4) {
    val customView = CustomComponent (this)
    val id = View.generateViewId()
    customView.id = id 
    ids.add(id)
    constraintLayout.addView(customView,i)
    flow.addView(customView)
}
flow.referencedIds = ids.toIntArray()

主要的内容就是这两句:constraintLayout.addView(customView,i)和

flow.referencedIds = ids.toIntArray()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值