Android 自定义ViewGroup 实现流式布局

学自鸿洋(hyman)的imooc视频


Android 自定义ViewGroup 实现流式布局_第1张图片  宽度不足自动换行。


FlowLayout

/**
 * author : stone
 * email  : [email protected]
 * time   : 15/8/4 15 08
 */
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 l, int t, int r, int b) {
        if (changed) {
            int w = getWidth(), h = getHeight();
            int tw = 0, th = 0;
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                if (tw + child.getMeasuredWidth() <= w) {

                } else {
                    tw = 0;
                    th += child.getMeasuredHeight();
                }
  
                child.layout(tw, th, tw+child.getMeasuredWidth(), th+child.getMeasuredHeight());
                tw += child.getMeasuredWidth();

                if (child instanceof TextView) {
                    ((TextView)child).setTextColor(getColor());
                }
            }
        }

    }

    /**
     * 随机颜色
     * @return
     */
    private int getColor() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        String temp;
        for (int i = 0; i < 3; i++) {
            temp = Integer.toHexString(random.nextInt(0xFF));
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            sb.append(temp);
        }
        return Color.parseColor("#" + sb.toString());
    }
}
  这里没考虑 子view高度不同的情况,也没考虑padding、margin的情况。


main.xml




    

    

ViewGroup.MarginLayoutParams 

  系统中ViewGroup的子类对应的LayoutParams都继承了MarginLayoutParams

  lp.leftMargin;  topMargin, rightMargin, bottomMargin  

view.getPaddingLeft  类似这样的方法,能拿到padding值


我的自定义View项目地址: https://github.com/aa86799/MyCustomView (欢迎start&fork)

本文地址:https://github.com/aa86799/MyCustomView/tree/master/flowlayout

你可能感兴趣的:(Android,自定义view,Android自定义View)