android 自定义ViewGroup实现流式布局过程

        谈到流式布局,有一种特性就是宽度不足,自动换行:

下面我们看看实现逻辑:

FlowLayout.java

package com.alex.flowlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class FlowLayout extends ViewGroup {  
	  
    public FlowLayout(Context context) {  
        this(context, null);  
    }  
  
    public FlowLayout(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    @Override  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
        measureChildren(widthMeasureSpec, heightMeasureSpec);  
    }  
  
    @Override  
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
        /** 
         * 一般是定义为int top;一个top实际上是数组的下标 
           left : 指定矩形框左上角的x坐标 
           top: 指定矩形框左上角的y坐标 
           right: 指定矩形框右下角的x坐标 
           bottom:指定矩形框右下角的y坐标 
         */  
        int width = getWidth();  
        int height = getHeight();  
        int tw = 0;  
        int th = 0;  
        for (int i = 0; i < getChildCount(); i++) {  
            View child = getChildAt(i);  
            if (tw + child.getWidth() < width) {  
  
            } else {  
                tw = 0;  
                th += child.getMeasuredHeight();   //超过屏幕的宽度,自动换行  
            }  
  
            child.layout(tw, th, tw + child.getMeasuredWidth(), th + child.getMeasuredHeight());  
            tw += child.getMeasuredWidth();  
        }  
    }  
}  

activity_main.xml

  
  
      
  
        

运行效果图如下:

android 自定义ViewGroup实现流式布局过程_第1张图片

你可能感兴趣的:(android进阶)