栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
  }

  
  @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 < childCount; i++){
      //获取当前控件
      View childAt = getChildAt(i);
      //获取宽度
      int cw = childAt.getMeasuredWidth();
      //获取高度
      int ch = childAt.getMeasuredHeight();
      //当前控件右边
      int cr = cl + cw;
      //当前控件下边
      int cb = ct + ch;
      //判断是否换行
      if(cr > 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 





  

效果图:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/158515.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号