使用FlexboxLayoutManager来实现流式布局
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:206
在项目中经常会用到流式布局,以前一直是使用鸿洋开源的哪个版本,然后在其上进行修改,之前看到了google开源了一个FlexboxLayoutManager的控件,也可以实现流式布局,但是一直也没有细看。今天偶然又见到一篇相关的文章,这里简单做一个记录,以备以后使用。
[官方地址](https://github.com/google/flexbox-layout)
这里注意,它默认给出的版本是androidX使用的,你看一下它下面的说明,非X使用的版本在里面有说明。
好不多说,直接上代码,这里的流式布局,采用的是RecyclerView + FlexboxLayoutManager来实现的。
我这里写到了fragment里,主要是当时为了试一下新写的懒惰加载功能。
fragment_one.xml
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_Flexbox"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</LinearLayout>
 
FragmentOne.java
public class FragmentOne extends BaseFragment {
    private RecyclerView rv_Flexbox;
    private List<String> list_data;
    private FlexBoxAdapter fAdapter;
    //private FlexboxLayoutManager flexboxLayoutManager;
    private Context mContext;
    public FragmentOne(Context mContext) {
        this.mContext = mContext;
    }
    @Override
    protected void initView(View rootView) {
        rv_Flexbox = (RecyclerView)rootView.findViewById(R.id.rv_Flexbox);
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(mContext);
        //flexDirection 属性决定主轴的方向(即项目的排列方向)。类似 LinearLayout 的 vertical 和 horizontal。
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);//主轴为水平方向,起点在左端。
        //flexWrap 默认情况下 Flex 跟 LinearLayout 一样,都是不带换行排列的,但是flexWrap属性可以支持换行排列。
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);//按正常方向换行
        //justifyContent 属性定义了项目在主轴上的对齐方式。
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);//交叉轴的起点对齐。
        rv_Flexbox.setLayoutManager(flexboxLayoutManager);
        list_data = new ArrayList<>();
        fAdapter = new FlexBoxAdapter(getActivity(),list_data);
        rv_Flexbox.setAdapter(fAdapter);
        fAdapter.setOnItemClickLitener(new FlexBoxAdapter.OnItemClickLitener() {
            @Override
            public void rel="stylesheet">
 







