美文网首页
自定义ViewGrop实现流式布局

自定义ViewGrop实现流式布局

作者: 梦止惰 | 来源:发表于2017-03-16 16:49 被阅读57次

参考了网上一些大神的思路和demo,自己也对onMeasure和onLayout方法的学习和总结,也自己实现了一个流式布局的自定义的viewGroup,算是对所学的自定义知识进行巩固。

一、简单的分析一下

大致思路是这样的:
1, 自定义一个viewGroup,重写里面的onMeasure和onLayout方法
2, 在onMeasure中对每个子view的宽高进行测量了,并且测量viewGroup的宽高
3, 在onLayout中算出每个子view的摆放的位置
在viewGroup中每一个item的margin是10,效果图是这样的:

Paste_Image.png

二、generateLayoutParams

因为我们只需要支持margin,所以直接使用系统的MarginLayoutParams

 * 返回当前的系统的MarginLayoutParams的值,因为我们需要用到margin
 *
 * @param attrs
 * @return
 */
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new MarginLayoutParams(getContext(), attrs);
}

三、onMeasure

  @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //取出系统的模式和大小
        int modeW = MeasureSpec.getMode(widthMeasureSpec);
        int sizeW = MeasureSpec.getSize(widthMeasureSpec);
        int modeH = MeasureSpec.getMode(heightMeasureSpec);
        int sizeH = MeasureSpec.getSize(heightMeasureSpec);
        //用来保存一行的宽高
        int lineW = 0, lineH = 0;
        //测量出来的宽高
        int width = 0, height = 0;
        //获取子控件的个数
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            //当前的子view
            View childAt = getChildAt(i);
            //测量每一个子控件的宽高
            measureChild(childAt, widthMeasureSpec, heightMeasureSpec);
            //获取MarginLayoutParams对象
            MarginLayoutParams params = (MarginLayoutParams) childAt.getLayoutParams();
            //此时子控件的宽高
            int childW = childAt.getMeasuredWidth() + params.leftMargin + params.rightMargin;
            int childH = childAt.getMeasuredHeight() + params.topMargin + params.bottomMargin;
            //判断当前这个子view的宽是否超过限定的宽度
            if (lineW + childW > sizeW) {//换行
                //宽度取最大的
                width = Math.max(lineW, childH);
                //从新记录下一行的宽度
                lineW = childW;
                //累加高度
                height += lineH;
                //记录下一行的高度
                lineH = childH;
            } else {
                lineW += childW;
                //行高取最大值
                lineH = Math.max(lineH, childH);
            }
            if (i == childCount - 1) {//在最后一行时的判断
                // width+=childW;
                width = Math.max(width, lineW);
                height += lineH;
            }
        }
        setMeasuredDimension(modeW == MeasureSpec.EXACTLY ? sizeW : width,
                modeH == MeasureSpec.EXACTLY ? sizeH : height);
    } 

首先拿出父类的模式和宽高,然后遍历每一个子控件,并且对每个子控件进行测量宽高,调用方法measureChild(),
再根据每一个子控件的宽高算出在wrap_content的情况下的viewGroup的宽高,如果是EXACTLY就直接使用父类宽高。

四、onLayout

 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //父控件的宽度(包含padding)
        int width = getWidth();
        //子控件在父控件中x轴方向上能显示的最大宽度
        int maxWidth = width - getPaddingRight();
        //最开始的位置的
        int baseLeft = getPaddingLeft();
        int baseTop = getPaddingTop();
        //当前的距左边和顶部的距离
        int currentLeft = baseLeft;
        int currentTop = baseTop;
        //表示当前view的left、top、right、bottom的位置
        int viewL = 0, viewT = 0, viewR = 0, viewB = 0;
        //子控件的个数
        int childCount = getChildCount();
        //用来保存要换行的上一个子view的高度
        int lastChildViewHeight = 0;
        for (int i = 0; i < childCount; i++) {
            //当前子view
            View childAt = getChildAt(i);
            if (childAt.getVisibility() == View.GONE) {
                continue;
            }
            //当前子view的MarginLayoutParams对象
            MarginLayoutParams params = (MarginLayoutParams) childAt.getLayoutParams();
            //子view实际的宽高包括margin
            int childWidth = childAt.getMeasuredWidth() + params.leftMargin + params.rightMargin;
            int childHeight = childAt.getMeasuredHeight() + params.topMargin + params.bottomMargin;
            if (currentLeft + childWidth > maxWidth) {//换行
                //此时距顶部距离累加
                currentTop += lastChildViewHeight;
                viewL = baseLeft + params.leftMargin;
                viewT = currentTop + params.topMargin;
                viewR = viewL + childAt.getMeasuredWidth();
                viewB = viewT + childAt.getMeasuredHeight();
                //由于此时是新的一行,所以currentLeft要从新开始
                currentLeft = baseLeft + childWidth;
            } else {//
                viewL = currentLeft + params.leftMargin;
                viewT = currentTop + params.topMargin;
                viewR = viewL + childAt.getMeasuredWidth();
                viewB = viewT + childAt.getMeasuredHeight();
                //当前距左边距离累加
                currentLeft += childWidth;
            }
            lastChildViewHeight = childHeight;
            childAt.layout(viewL, viewT, viewR, viewB);
        }
    }

在这里我是计算了父控件的padding的,然后算出每一个子控件在父控件的位置(即left、right、top、bottom),调用layout()方法,将每一个子控件放在父控件内

五、动态的调用

1,在主activity的xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_flow_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.contactlistapplication.testcustomview.flow.FlowLayoutActivity">
  <com.example.contactlistapplication.testcustomview.flow.FlowLayout
      android:id="@+id/flowLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
       android:background="@android:color/holo_green_light">

  </com.example.contactlistapplication.testcustomview.flow.FlowLayout>
</RelativeLayout>

2,子控件的xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/textview_bg"
        android:text="Test" />

3,shape属性

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <padding android:left="5dp" android:right="5dp" android:bottom="5dp" android:top="5dp"/>
    <gradient
        android:angle="45"
        android:endColor="#99aa55"
        android:startColor="#06fffa" />
</shape>

4,activity中的代码

public class FlowLayoutActivity extends AppCompatActivity {

    private FlowLayout flowLayout;
    private String[] strs = new String[]{"今日发表", "李彦宏", "署名文章", "在人工智能","这场科技","浪潮中", "中国", "与其他", "国家"
            , "站在同一起跑线上", "中国的科学家", "工程师", "企业家必须全力以赴", "让这一次", "的全球科技创新",
            "尽快迈入", "让我们每个人", "都激动万分的中国时刻"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flow_layout);
        flowLayout = (FlowLayout) findViewById(R.id.flowLayout);
        init();
    }

    private void init() {
        TextView textView = null;
        for (String str : strs) {
            View inflate = LayoutInflater.from(this).inflate(R.layout.item_text, flowLayout, false);
            textView = (TextView) inflate.findViewById(R.id.textView);
            textView.setText(str);
            flowLayout.addView(textView);
        }

    }
}

相关文章

网友评论

      本文标题:自定义ViewGrop实现流式布局

      本文链接:https://www.haomeiwen.com/subject/tfsjnttx.html