SimpleFlowLayout:一个简易的横向流式布局,只实现核心功能,使用者可自行扩展
Demo图片如下所示:
SimpleFlowLayout直接继承自ViewGroup,主要负责实现的功能点为:
- 自定义属性:提供每行Item间距,行与行之间的间距属性,方便使用者更改
- onMeasure()测量方法: 负责测量当宽度和高度为MatchParent和WrapContent以及SimpleFlowLayout被嵌套在ScrollView或者NestedScrollView中时的measure情况,还有使用Padding的情况
- onLayout()摆放方法:直接继承自ViewGroup时必须要实现的方法
一、实现自定义属性:
在Values下新建attrs.xml属性文件,加入自定义属性
<resources>
<declare-styleable name="SimpleFlowLayout">
<attr name="hor_divider_width" format="dimension"/>
<attr name="hor_row_height" format="dimension"/>
</declare-styleable>
</resources>
其次在布局文件中使用
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<!--hor_divider_width:每行的Item间距
hor_row_height:行间距-->
<com.wjr.simple_flow_layout.SimpleFlowLayout
android:id="@+id/flow_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
app:hor_divider_width="15dp"
app:hor_row_height="15dp"/>
</android.support.v4.widget.NestedScrollView>
最后在自定义View中获取到自定义属性
public SimpleFlowLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes