FlexboxLayout的认识与使用
2019-08-05 本文已影响0人
难得糊涂与君勉
简介
它类似于LinearLayout与RelativeLayout。不同的是它具有换行特性,可以将子视图进行自动换行的效果(看下面运行效果就一目了然)。
官方地址
获取
dependencies {
implementation 'com.google.android:flexbox:1.1.0'
}
需要注意的是这个版本的已经适配了androidx,如果你的项目没有适配android x ,那么运行的时候会出现如下错误:
java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/core/view/ViewCompat;
那么需要你使用下面的依赖:
implementation 'com.google.android:flexbox:1.0.0'
使用
属性介绍第一部分

看了上面的属性肯定是一脸懵逼,经过研究花了下面的两张图,方便理解:
起点:在FlexBoxLayout容器中开始放置第一个子View的点。

示例 1
当app:flexDirection = row ,app:flexWrap = wrap_reverse :
看图就是在FlexBoxLayout的左下角开始放置第一个子View,然后向上自动换行的一个效果:

tip 示例中子View都是按照第一个,第二个此类顺序放入FlexBoxLayout中的,设置的FlexBoxLayotu固定高度200dp。

示例2
如果app:flexDirection=column , app:flexWrap = wrap_reverse
,会在FlexBoxLayout右上角,向下排列,往左换行的效果,效果如图:

属性介绍第二部分

示例3 space_around

示例4 center

属性介绍三

还有其他属性,暂且不介绍了
每个子View的可选属性

tip2 个人感觉这样以图表方式介绍更加直接,运行效果自己一跑就ok
给RecyclerView的使用
RecyclerView recyclerView = (RecyclerView) context.findViewById(R.id.recyclerview);
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
layoutManager.setFlexDirection(FlexDirection.COLUMN);
layoutManager.setJustifyContent(JustifyContent.FLEX_END);
recyclerView.setLayoutManager(layoutManager);
对于FlexboxLayoutManager的子项的属性,您可以这样做:
mImageView.setImageDrawable(drawable);
ViewGroup.LayoutParams lp = mImageView.getLayoutParams();
if (lp instanceof FlexboxLayoutManager.LayoutParams) {
FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
flexboxLp.setFlexGrow(1.0f);
flexboxLp.setAlignSelf(AlignSelf.FLEX_END);
}