Android 流式布局实现方式

文章介绍了三种在Android中实现流式布局的方法:1)使用FlexboxLayout,通过设置flexWrap和flexDirection属性实现;2)结合RecyclerView和FlexboxLayoutManager,调整布局方向和对齐方式;3)利用ConstraintLayout的Flow特性,设置约束和间隔来创建流式布局。

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

Android 流式布局实现方式

1、FlexboxLayout

FlexboxLayout是Google开源的一个强大的控件,直接继承ViewGroup。

dependencies {
    implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
<com.google.android.flexbox.FlexboxLayout
    android:id="@+id/fl_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
var flContent = findViewById<FlexboxLayout>(R.id.fl_content)
        flContent.flexWrap = FlexWrap.WRAP
        flContent.flexDirection = FlexDirection.ROW
        map.keys?.forEach {
            flContent.layoutInflate(R.layout.item_filter).apply {
                var tvName = this.findViewById<TextView>(R.id.tv_name)
                tvName.text = it
                tag = false
  
                flContent.addView(this)
            }
        }

2、Recyclerview+FlexboxLayoutManager

implementation 'com.google.android:flexbox:3.0.0'//Android官方流式布局
FlexboxLayoutManager layoutManager=new FlexboxLayoutManager(this);
layoutManager.setFlexDirection(FlexDirection.ROW);
//layoutManager.setJustifyContent(JustifyContent.CENTER);
//layoutManager.setAlignItems(AlignItems.CENTER);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setAdapter(adapter);

3、ConstraintLayout + Flow

Constraintlayout 2.0 新增了Flow流式虚拟布局。

implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
  <androidx.constraintlayout.helper.widget.Flow
        android:id="@+id/flow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="tvA,tvB,tvC,tvD,tvE,tvF,tvG"
        app:flow_horizontalGap="30dp" //View水平间隔
        app:flow_verticalGap="30dp" //垂直间隔
        app:flow_wrapMode="none"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
for (i in 0..4) {
    val customView = CustomComponent (this)
    customView.id = generateViewId()
    constraintLayout.addView(customView,i)
    flow.addView(customView)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值