网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Android中怎么利用ViewGroup自定义布局

今天就跟大家聊聊有关Android中怎么利用ViewGroup自定义布局,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

成都创新互联公司专注于石城网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供石城营销型网站建设,石城网站制作、石城网页设计、石城网站官网定制、成都微信小程序服务,打造石城网络公司原创品牌,更为您提供石城网站排名全网营销落地服务。

首先,如果是一个 LinearLayout 那么当设置 wrap_content 时,他就会以子空间中最宽的那个为它的宽度。同时在高度方面会是所有子控件高度的总和。所以我们先写两个方法,分别用于测量 ViewGroup 的宽度和高度。

private int getMaxWidth(){  int count = getChildCount();  int maxWidth = 0;  for (int i = 0 ; i < count ; i ++){   int currentWidth = getChildAt(i).getMeasuredWidth();   if (maxWidth < currentWidth){    maxWidth = currentWidth;   }  }  return maxWidth; }  private int getTotalHeight(){  int count = getChildCount();  int totalHeight = 0;  for (int i = 0 ; i < count ; i++){   totalHeight += getChildAt(i).getMeasuredHeight();  }  return totalHeight; }

对于 ViewGroup 而言我们可以粗略的分为两种模式:固定长宽模式(match_parent),自适应模式(wrap_content),根据这两种模式,就可以对 ViewGroup 的绘制进行划分。这里关于 measureChildren 这个方法,他是用于将所有的子 View 进行测量,这会触发每个子 View 的 onMeasure 函数,但是大家要注意要与 measureChild 区分,measureChild 是对单个 view 进行测量

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  super.onMeasure(widthMeasureSpec, heightMeasureSpec);   measureChildren(widthMeasureSpec, heightMeasureSpec);   int widthMode = MeasureSpec.getMode(widthMeasureSpec);  int width  = MeasureSpec.getSize(widthMeasureSpec);  int heightMode= MeasureSpec.getMode(heightMeasureSpec);  int height = MeasureSpec.getSize(heightMeasureSpec);   if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){   int groupWidth = getMaxWidth();   int groupHeight= getTotalHeight();    setMeasuredDimension(groupWidth, groupHeight);  }else if (widthMode == MeasureSpec.AT_MOST){   setMeasuredDimension(getMaxWidth(), height);  }else if (heightMode == MeasureSpec.AT_MOST){   setMeasuredDimension(width, getTotalHeight());  } }

重写 onLayout

整完上面这些东西,我们的布局大小七十九已经出来了,然我们在活动的布局文件里面加上它,并添加上几个子 View 然后运行一下,先看看效果:

 

其他资讯