一、概述:
(一)、什么是FlowLayout?
何为FlowLayout,就是控件根据ViewGroup的宽,自动的往右添加,如果当前行剩余空间不足,则自动添加到下一行。有点所有的控件都往左飘的感觉,第一行满了,往第二行飘,所以也叫流式布局。
Android并没有提供流式布局,但是某些场合中,流式布局还是非常适合使用的,比如关键字标签,搜索热词列表等,如下图:
这些都特别适合使用FlowLayout,github已经有了这样FlowLayout,当然使用我们自己定义的FlowLayout实现上面的标签效果,就不仅仅是学会使用一个控件,而是学会写一个控件。
二、制作步骤:
(一)、分析
1、对于FlowLayout,需要指定的LayoutParams,我们目前只需要能够识别margin即可,即使用MarginLayoutParams.
2、onMeasure中计算所有childView的宽和高,然后根据childView的宽和高,计算自己的宽和高。(当然,如果不是wrap_content,直接使用父ViewGroup传入的计算值即可)
3、onLayout中对所有的childView进行布局。
(二)、generateLayoutParams
因为我们只需要支持margin,所以直接使用系统的MarginLayoutParams
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
(三)、onMeasure
/**
* 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获得它的父容器为它设置的测量模式和大小
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
Log.e(TAG, sizeWidth + "," + sizeHeight);
// 如果是warp_content情况下,记录宽和高
int width = 0;
int height = 0;
/**
* 记录每一行的宽度,width不断取最大宽度
*/
int lineWidth = 0;
/**
* 每一行的高度,累加至height
*/
int lineHeight = 0;
int cCount = getChildCount();
// 遍历每个子元素
for (int i = 0; i < cCount; i++)
{
View child = getChildAt(i);
// 测量每一个child的宽和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
// 得到child的lp
MarginLayoutParams lp = (MarginLayoutParams) child
.getLayoutParams();
// 当前子空间实际占据的宽度
int childWidth = child.getMeasuredWidth() + lp.leftMargin
+ lp.rightMargin;
// 当前子空间实际占据的高度
int childHeight = child.getMeasuredHeight() + lp.topMargin
+ lp.bottomMargin;
/**
* 如果加入当前child,则超出最大宽度,则的到目前最大宽度给width,类加height 然后开启新行
*/
if (lineWidth + childWidth > sizeWidth)
{
width = Math.max(lineWidth, childWidth);// 取最大的
lineWidth = childWidth; // 重新开启新行,开始记录
// 叠加当前高度,
height += lineHeight;
// 开启记录下一行的高度
lineHeight = childHeight;
} else
// 否则累加值lineWidth,lineHeight取最大高度
{
lineWidth += childWidth;
lineHeight = Math.max(lineHeight, childHeight);
}
// 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较
if (i == cCount - 1)
{
width = Math.max(width, lineWidth);
height += lineHeight;
}
}
setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth
: width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight
: height);
}
首先得到其父容器传入的测量模式和宽高的计算值,然后遍历所有的childView,使用measureChild方法对所有的childView进行测量。然后根据所有childView的测量得出的宽和高得到该ViewGroup如果设置为wrap_content时的宽和高。最后根据模式,如果是MeasureSpec.EXACTLY则直接使用父ViewGroup传入的宽和高,否则设置为自己计算的宽和高。
(四)、onLayout
onLayout中完成对所有childView的位置以及大小的指定
/**
* 存储所有的View,按行记录
*/
private List<List<View>> mAllViews = new ArrayList<List<View>>();
/**
* 记录每一行的最大高度
*/
private List<Integer> mLineHeight = new ArrayList<Integer>();
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
mAllViews.clear();
mLineHeight.clear();
int width = getWidth();
int lineWidth = 0;
int lineHeight = 0;
// 存储每一行所有的childView
List<View> lineViews = new ArrayList<View>();
int cCount = getChildCount();
// 遍历所有的孩子
for (int i = 0; i < cCount; i++)
{
View child = getChildAt(i);
MarginLayoutParams lp = (MarginLayoutParams) child
.getLayoutParams();
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();
// 如果已经需要换行
if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)
{
// 记录这一行所有的View以及最大高度
mLineHeight.add(lineHeight);
// 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView
mAllViews.add(lineViews);
lineWidth = 0;// 重置行宽
lineViews = new ArrayList<View>();
}
/**
* 如果不需要换行,则累加
*/
lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
lineViews.add(child);
}
// 记录最后一行
mLineHeight.add(lineHeight);
mAllViews.add(lineViews);
int left = 0;
int top = 0;
// 得到总行数
int lineNums = mAllViews.size();
for (int i = 0; i < lineNums; i++)
{
// 每一行的所有的views
lineViews = mAllViews.get(i);
// 当前行的最大高度
lineHeight = mLineHeight.get(i);
Log.e(TAG, "第" + i + "行 :" + lineViews.size() + " , " + lineViews);
Log.e(TAG, "第" + i + "行, :" + lineHeight);
// 遍历当前行所有的View
for (int j = 0; j < lineViews.size(); j++)
{
View child = lineViews.get(j);
if (child.getVisibility() == View.GONE)
{
continue;
}
MarginLayoutParams lp = (MarginLayoutParams) child getLayoutParams();
//算childView的left,top,right,bottom
int lc = left + lp.leftMargin;
int tc = top + lp.topMargin;
int rc =lc + child.getMeasuredWidth();
int bc = tc + child.getMeasuredHeight();
Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r =" + rc + " , b = " + bc);
child.layout(lc, tc, rc, bc);
left += child.getMeasuredWidth() + lp.rightMargin + lp.leftMargin;
}
left = 0;
top += lineHeight;
}
}
allViews的每个Item为每行所有View的List集合。
mLineHeight记录的为每行的最大高度。
23-48行,遍历所有的childView,用于设置allViews的值,以及mLineHeight的值。
57行,根据allViews的长度,遍历所有的行数
67-91行,遍历每一行的中所有的childView,对childView的left , top , right , bottom 进行计算,和定位。
92-93行,重置left和top,准备计算下一行的childView的位置。
好了,到此完成了所有的childView的绘制区域的确定,到此,我们的FlowLayout的代码也结束了~~静下心来看一看是不是也不难~
(五)、测试
使用TextView作为我们的标签,所以为其简单写了一点样式:
res/values/styles.xml中:
[xml]
<style name="text_flag_01">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_margin">4dp</item>
<item name="android:background">@drawable/flag_01</item>
<item name="android:textColor">#ffffff</item>
</style>
flag_01.xml
[xml]
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#7690A5" >
</solid>
<corners android:radius="5dp"/>
<padding
android:bottom="2dp"
android:left="10dp"
android:right="10dp"
android:top="2dp" />
</shape>
布局文件:
[xml]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E1E6F6"
android:orientation="vertical" >
<com.zhy.zhy_flowlayout02.FlowLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
style="@style/text_flag_01"
android:text="Welcome" />
<TextView
style="@style/text_flag_01"
android:text="IT工程师" />
<TextView
style="@style/text_flag_01"
android:text="学习ing" />
<TextView
style="@style/text_flag_01"
android:text="恋爱ing" />
<TextView
style="@style/text_flag_01"
android:text="挣钱ing" />
<TextView
style="@style/text_flag_01"
android:text="努力ing" />
<TextView
style="@style/text_flag_01"
android:text="I thick i can" />
</com.zhy.zhy_flowlayout02.FlowLayout>
</LinearLayout>
res/drawble/flog_02.xml
[xml]
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" >
</solid>
<corners android:radius="40dp"/>
<stroke android:color="#C9C9C9" android:width="2dp"/>
<padding
android:bottom="2dp"
android:left="10dp"
android:right="10dp"
android:top="2dp" />
</shape>
flag_03.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" >
</solid>
<corners android:radius="40dp"/>
<padding
android:bottom="2dp"
android:left="10dp"
android:right="10dp"
android:top="2dp" />
</shape>
布局文件:
[xml]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E1E6F6"
android:orientation="vertical" >
<com.zhy.zhy_flowlayout02.FlowLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
style="@style/text_flag_01"
android:text="Welcome" />
<TextView
style="@style/text_flag_01"
android:text="IT工程师" />
<TextView
style="@style/text_flag_01"
android:text="学习ing" />
<TextView
style="@style/text_flag_01"
android:text="恋爱ing" />
<TextView
style="@style/text_flag_01"
android:text="挣钱ing" />
<TextView
style="@style/text_flag_01"
android:text="努力ing" />
<TextView
style="@style/text_flag_01"
android:text="I thick i can" />
</com.zhy.zhy_flowlayout02.FlowLayout>
<com.zhy.zhy_flowlayout02.FlowLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="Welcome"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="IT工程师"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="学习ing"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="恋爱ing"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="挣钱ing"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="努力ing"
android:textColor="#888888" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_02"
android:text="I thick i can"
android:textColor="#888888" />
</com.zhy.zhy_flowlayout02.FlowLayout>
<com.zhy.zhy_flowlayout02.FlowLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="Welcome"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="IT工程师"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="学习ing"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="恋爱ing"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="挣钱ing"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="努力ing"
android:textColor="#43BBE7" />
<TextView
style="@style/text_flag_01"
android:background="@drawable/flag_03"
android:text="I thick i can"
android:textColor="#43BBE7" />
</com.zhy.zhy_flowlayout02.FlowLayout>
</LinearLayout>
Activity
public class MainActivity extends AppCompatActivity {
private Context context;
private int dimens;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flowalyout_main);
context = this;
FlowLayoutM flowLayout = (FlowLayoutM) findViewById(R.id.flow_layout);
dimens = getDimens(R.dimen.common10dp);
flowLayout.setVerticalSpacing(dimens);
flowLayout.setHorizontalSpacing(dimens);
flowLayout.setPadding(dimens, dimens, dimens, dimens);
final ArrayList<String> list = getString();
if(list != null){
for(int g = 0; g < list.size(); g++){
TextView tv = new TextView(MainActivity.this);
tv.setText(list.get(g));
tv.setTextColor(Color.CYAN);
tv.setTextSize(16);
tv.setGravity(Gravity.CENTER);
tv.setPadding(dimens,dimens,dimens,dimens);
Drawable pressed = createDrawable(getRadmoColor(),dimens);
Drawable normal = createDrawable(getRadmoColor(),dimens);
tv.setBackgroundDrawable(createSelector(pressed,normal));//设置按下的颜色
flowLayout.addView(tv);
final int finalG = g;
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,list.get(finalG).toString(),Toast.LENGTH_SHORT).show();
}
});
}
}
}
public static int getRadmoColor(){
Random random = new Random();
return Color.rgb(random.nextInt(150),random.nextInt(150),random.nextInt(150));
}
public static Drawable createSelector(Drawable pressed, Drawable normal){
StateListDrawable drawable = new StateListDrawable();
//添加按压状态以及图图片
drawable.addState(new int[]{android.R.attr.state_pressed},pressed);
//添加正常状态以及图片
drawable.addState(new int[]{},normal);
//设置状态选择器的过渡动画,让其平滑的执行
drawable.setEnterFadeDuration(500);
drawable.setExitFadeDuration(500);
return drawable;
}
public static Drawable createDrawable(int color, float radius){
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);//设置形状为圆角矩形
drawable.setColor(color);//设置颜色
drawable.setCornerRadius(radius);//设置角度
return drawable;
}
public static ArrayList<String> getString() {
ArrayList<String> list = new ArrayList<>();
String[] info = new String[]{};//设置数据
for(int i = 0; i < info.length;i++){
list.add(info[i]);
}
return list;
}
public int getDimens(int id){
return context.getResources().getDimensionPixelSize(id);
}
}
FlowLayout
public class FlowLayoutM extends ViewGroup {
public int horizontalSpacing;//水平间距
public int verticalSpacing;//竖直间距
public ArrayList<Line> lineList;
public FlowLayoutM(Context context) {
super(context,null);
}
public FlowLayoutM(Context context, AttributeSet attrs) {
super(context, attrs,0);
}
public FlowLayoutM(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setHorizontalSpacing(int horizontalSpacing) {
this.horizontalSpacing = horizontalSpacing;
}
public void setVerticalSpacing(int verticalSpacing) {
this.verticalSpacing = verticalSpacing;
}
/**
* 分行:遍历所有的子View,判断哪几个子View在同一行(排座位表)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//一.测量需用多大
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//lineList.clear();
lineList = new ArrayList<>();
System.out.println("================onMeasure()方法");
int width = MeasureSpec.getSize(widthMeasureSpec);//1.FlowLayout的宽度,也就是申请宽度
int noPaddingWidth = width - getPaddingLeft() - getPaddingRight();//获取用于实际比较的宽度,就是除去2边的padding的宽度
Line line = new Line();
for(int i = 0; i < getChildCount();i++){//3.遍历所有的子View,拿子View的宽和noPaddingWidth进行比较
View views = getChildAt(i);
views.measure(0,0);//保证能够获取到宽高
if(line.getViewList().size() == 0){//4.如果当前line中木有子View,则不用比较直接放入line中,因为要保证每行至少有一个子View;
line.addLineView(views);
}else if(line.getLineWidth() + horizontalSpacing + views.getMeasuredWidth() > noPaddingWidth){//5.如果当前line的宽+水平间距+子View的宽大于noPaddingWidth,则child需要换行
lineList.add(line);
line = new Line();
line.addLineView(views);
}else {
line.addLineView(views);
}
if(i == getChildCount() - 1){ //6.如果当前child是最后的子View,那么需要保存最后的line对象
lineList.add(line);
}
}
int height = getPaddingTop() + getPaddingBottom();//申请高度
for(int i = 0; i < lineList.size();i++){
height +=lineList.get(i).getLineHeight();
}
height += (lineList.size() - 1) * verticalSpacing;
setMeasuredDimension(width,height);//7.设置当前控件的宽高,或者向父VIew申请宽高
System.out.println("======width="+width+",height="+height);
}
//// TODO: 2017/3/24 怎么能获取到宽高呢?
/**
* views.measure(0,0);//保证能够获取到宽高
* view.getMeasureHeight();//得到控件高度,注意在创建的时候是得不到的
* //保证能得到
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//一般用完立即移除,因为只有该view的宽高改变都会再引起回调该方法
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
*/
/**
* 去摆放所有的子View,让每个人真正的坐到自己的位置上
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) { //二.画布就开销多大
System.out.println("================onLayout()方法");
int paddingTop = getPaddingTop();
int paddingLeft = getPaddingLeft();
for(int i = 0; i < lineList.size();i++){//1.获取line的view的集合
Line line = lineList.get(i);
if(i > 0){//从第二行要加行距
paddingTop += verticalSpacing + lineList.get(i - 1).getLineHeight();
}
ArrayList<View> viewList = line.getViewList();
int reMainSpacing = getReMainSpacing(line);//计算空白空间
int spacing = reMainSpacing / viewList.size();
for(int j = 0; j < viewList.size(); j++){//2.获取每一行的子view的集合
View view = viewList.get(j);
int specWidth = MeasureSpec.makeMeasureSpec(view.getMeasuredWidth() + spacing, MeasureSpec.EXACTLY);
view.measure(specWidth,MeasureSpec.UNSPECIFIED);////保证能够获取到宽高
if(j == 0){//如果是第一个子view就放在左边就可以了
view.layout(paddingLeft,paddingTop,paddingLeft + view.getMeasuredWidth(),paddingTop + view.getMeasuredHeight());
}else{
View viewLast = viewList.get(j - 1);
int left = viewLast.getRight() + horizontalSpacing;
view.layout(left,viewLast.getTop(),left+ view.getMeasuredWidth(),viewLast.getBottom());
}
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
System.out.println("================onDraw()方法");
}
/**
* 获取每行空白的宽度
*/
public int getReMainSpacing(Line line){
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - line.getLineWidth();//测量的宽分别减去...
}
/**
* 封装每行的数据
*/
class Line{
int width;
int height;
ArrayList<View> viewList;
public Line() {
viewList = new ArrayList<>();
}
/**
* 换行的方法
*/
public void addLineView(View child){
if(!viewList.contains(child)){
viewList.add(child);
if(viewList.size() == 1){
width = child.getMeasuredWidth();
}else{
width += child.getMeasuredWidth() + horizontalSpacing;
}
}
height = Math.max(height,child.getMeasuredHeight());
}
/**
* 获取当前行的宽度
* @return
*/
public int getLineWidth(){
return width;
}
/**
* 获取当前行的高度
* @return
*/
public int getLineHeight(){
return height;
}
/**
* 获取当前行的所有子view
* @return
*/
public ArrayList<View> getViewList(){
return viewList;
}
}
}