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

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

一、效果图

当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.csdn.net/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
`display: flex;` 是 CSS 中的一个属性,用于创建弹性盒子布局。当您将 `display: flex;` 应用于某个容器元素上时,该容器内的所有子元素都将按照弹性盒子布局规则排列。 若要在 flex 容器内让第一个元素宽度固定而允许第二个元素超出宽度自动换行,则您可以采用以下方法: ### 示例代码 ```html <div class="container"> <div class="fixed-width">固定宽度内容</div> <div class="flexible-width">可变宽度的内容</div> </div> <style> .container { display: flex; } .fixed-width { width: 200px; /* 设置第一个元素的具体宽度 */ } .flexible-width { width: auto; /* 设置第二个元素的宽度为自动 */ } </style> ``` 在这段代码中: 1. **容器类** `.container` 使用了 `display: flex;` 属性,这意味着它的直接子元素将以弹性布局排列。 2. **固定宽度类** `.fixed-width` 指定了具体的宽度(这里设置为200px),所以这个元素会被强制保持这个宽度。 3. **可变宽度类** `.flexible-width` 将其宽度设置为 `auto`,意味着浏览器会根据其内部内容自动调整宽度,并可能导致换行。 ### 相关问题: 1. 当我需要将某些元素设为固定宽度并且希望其他元素能够溢出并自动换行时,如何使用 flexbox 实现这一效果? 2. 我可以使用 flex 容器的哪些属性来控制子元素的自动换行行为? 3. 如果我在 flex 容器中添加了一个新的子元素,它超过了可用空间怎么办?
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值