Android 自定义ViewGroup 实现流式布局

学自鸿洋(hyman)的imooc视频


  宽度不足自动换行。


FlowLayout

/**
 * author : stone
 * email  : aa86799@163.com
 * 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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.stone.flowlayout.view.FlowLayout
        android:id="@+id/fl_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </com.stone.flowlayout.view.FlowLayout>
</LinearLayout>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值