版权声明:本文为HaiyuKing原创文章,转载请注明出处!
前言
FlexboxLayout是一个Google 开源的库项目,它将CSS Flexible Box Layout Module的类似功能 引入Android。
这里只记录FlexboxLayoutManager搭配RecyclerView实现流式布局的实现方式,至于FlexboxLayout的独立使用以及相关资料,请阅读《参考资料》。
效果图
代码分析
将FlexboxLayoutManager理解为RecyclerView的一种manager,比如LinearLayoutManager等。
//设置布局管理器 FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(MainActivity.this); //flexDirection 属性决定主轴的方向(即项目的排列方向)。类似 LinearLayout 的 vertical 和 horizontal。 flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);//主轴为水平方向,起点在左端。 //flexWrap 默认情况下 Flex 跟 LinearLayout 一样,都是不带换行排列的,但是flexWrap属性可以支持换行排列。 flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);//按正常方向换行 //justifyContent 属性定义了项目在主轴上的对齐方式。 flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);//交叉轴的起点对齐。 mRecyclerView.setLayoutManager(flexboxLayoutManager);
使用步骤
一、项目组织结构图
注意事项:
1、 导入类文件后需要change包名以及重新import R文件路径
2、 Values目录下的文件(strings.xml、dimens.xml、colors.xml等),如果项目中存在,则复制里面的内容,不要整个覆盖
二、导入步骤
(1)在build.gradle中引用recyclerview【版本号和appcompat保持一致】和Flexboxlayout
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.why.project.recyclerflexboxlayoutmanagerdemo"
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//RecyclerView
compile "com.android.support:recyclerview-v7:27.1.1"
//FlexboxLayout
implementation 'com.google.android:flexbox:1.0.0'
}
(2)在项目中实现Recyclerview基本数据展现
1、创建Bean类
package com.why.project.recyclerflexboxlayoutmanagerdemo.bean; import java.util.Date; /** * Created by HaiyuKing * Used 搜索历史记录bean */ public class SearchHistoryBean { private String searchTitle;//搜索的标题 private Date searchDate;//搜索的时间(如果重新搜索了的话,只需要更新搜索时间即可,不需要添加) public String getSearchTitle() { return searchTitle; } public void setSearchTitle(String searchTitle) { this.searchTitle = searchTitle; } public Date getSearchDate() { return searchDate; } public void setSearchDate(Date searchDate) { this.searchDate = searchDate; } }