android流式布局onLayout()方法详解

这篇文章主要为大家详细介绍了android流式布局的onLayout()方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

在上一篇中及就写了自定义view中的onMeausre()和onDraw()两个方法。在这里就用简单的流式布局来介绍一下onLayout()方法。

在onLayout方法中有四个参数,我画了一个简单的图来分清楚值哪里。

 

好啦,现在就直接看代码吧。

FlowLayout.Java 

 package com.example.my_view; 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) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } /** * * @param changed * @param l 左 * @param t 上 * @param r  右 * @param b  下 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { //获得子控件的数量 int childCount = getChildCount(); //当前子控件的左边坐标 int cl = 0; //当前子控件的上边坐标 int ct = 0; //ViewGroup整体宽度 int width = r - l; //行高 int lineHeight = 0; //遍历所有子控件 for(int i = 0; i  width){ //如果换行重新计算上下左右地值 cl = 0; cr = cl + cw; ct += lineHeight; cb = ct + ch; //换行后,第一个控件作为最大行高 lineHeight = ch; }else{ //如果不换行,需要计算最大高度 lineHeight = Math.max(lineHeight,ch); } childAt.layout(cl,ct,cr,cb); //横向向后移动一个,前面控件的右边作为后面控件的左边 cl = cr; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //测量所有子控件 measureChildren(widthMeasureSpec, heightMeasureSpec); } } 

activity_main.xml 

  

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持html中文网。

以上就是android流式布局onLayout()方法详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 移动