Recyclerview + Flexbox水平排列超出页面宽度自动换行

本文展示了如何在Android中使用RecyclerView结合FlexboxLayout实现当item宽度超出屏幕时自动换行的效果。通过引入Google的Flexbox布局库,并添加相关依赖,可以实现类似CSS Flexbox的功能。详细代码和原理将在后续部分讲解。

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

一、效果图

当item行宽度超出页面宽度的时候,自动换行
自动换行

二、实现

FlexboxLayout ,github https://github.com/google/flexbox-layout
官方原话简介:FlexboxLayout is a library project which brings the similar capabilities of CSS Flexible Box Layout Module to Android.

具体属性详解,这篇博文很清楚:https://blog.youkuaiyun.com/weixin_39397471/article/details/90257522

gradle中添加依赖:

dependencies {
    implementation 'com.google.android:flexbox:2.0.1'
}

如果项目中没有转化为AndroidX,使用1.0.0版本

通过代码设置属性

FlexboxLayoutManager flManager = new FlexboxLayoutManager(this);
//
flManager.setFlexWrap(FlexWrap.WRAP);
//设置主轴的方向
flManager.setFlexDirection(FlexDirection.ROW);
mFlexRecyclerView.setLayoutManager(flManager);
FlexWrap.WRAP:当内容超过一行,自动换行
FlexWrap.NOWRAP:单行显示不换行,默认值
FlexWrap.WRAP_REVERSE:反向换行,下一行内容在这一行上方
/**
  * Main axis direction -> horizontal. Main start to
  * main end -> Left to right (in LTR languages).
  * Cross start to cross end -> Top to bottom
  */
FlexDirection.ROW:主轴方向按照水平方向排列

/**
  * Main axis direction -> horizontal. Main start
  * to main end -> Right to left (in LTR languages). Cross start to cross end ->
  * Top to bottom.
  */
FlexDirection.ROW_REVERSE:主轴方向按照水平方向反向排版(从右侧开始排列)

/**
  * Main axis direction -> vertical. Main start
  * to main end -> Top to bottom. Cross start to cross end ->
  * Left to right (In LTR languages).
  */
FlexDirection.COLUMN:主轴方向按竖直方向排版

/**
  * Main axis direction -> vertical. Main start
  * to main end -> Bottom to top. Cross start to cross end -> Left to right
  * (In LTR languages)
  */
FlexDirection.COLUMN_REVERSE:主轴方向按竖直方向反向排版(从下方开始排列)

具体代码:

public class FlexActivity extends AppCompatActivity implements IMoveAndSwipeCallback{

    private RecyclerView mFlexRecyclerView;
    private List<Str
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值