热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

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 

<&#63;xml version="1.0" encoding="utf-8"&#63;>



  

效果图:

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


推荐阅读
author-avatar
棉布缺嘴_621
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有