您的位置:首页 > 移动开发 > Android开发

Android 自定义ViewGroup 实现流式布局

2015-08-05 14:42 477 查看
学自鸿洋(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: