[Android Pro] Android开发实践:自定义ViewGroup的onLayout()分析
reference to : http://www.linuxidc.com/Linux/2014-12/110165.htm
前一篇文章主要讲了自定义View为什么要重载onMeasure()方法(见 http://www.linuxidc.com/Linux/2014-12/110164.htm),那么,自定义ViewGroup又都有哪些方法需要重载或者实现呢 ?
Android开 发中,对于自定义View,分为两种,一种是自定义控件(继承View类),另一种是自定义布局容器(继承ViewGroup)。如果是自定义控件,则一 般需要重载两个方法,一个是onMeasure(),用来测量控件尺寸,另一个是onDraw(),用来绘制控件的UI。而自定义布局容器,则一般需要实 现/重载三个方法,一个是onMeasure(),也是用来测量尺寸;一个是onLayout(),用来布局子控件;还有一个是 dispatchDraw(),用来绘制UI。
本文主要分析自定义ViewGroup的onLayout()方法的实现。
ViewGroup类的onLayout()函数是abstract型,继承者必须实现,由于ViewGroup的定位就是一个容器,用来盛放子控 件的,所以就必须定义要以什么的方式来盛放,比如LinearLayout就是以横向或者纵向顺序存放,而RelativeLayout则以相对位置来摆 放子控件,同样,我们的自定义ViewGroup也必须给出我们期望的布局方式,而这个定义就通过onLayout()函数来实现。
我们通过实现一个水平优先布局的视图容器来更加深入地了解onLayout()的实现吧,效果如图所示(黑色方块为子控件,白色部分为自定义布局容器)。该容器的布局方式是,首先水平方向上摆放子控件,水平方向放不下了,则另起一行继续水平摆放。

1. 自定义ViewGroup的派生类
第一步,则是自定ViewGroup的派生类,继承默认的构造函数。
public class CustomViewGroup extends ViewGroup {
public CustomViewGroup(Context context) {
super(context);
}
public CustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomViewGroup(Context context, AttributeSet attrs, intdefStyle) {
super(context, attrs, defStyle);
}
}
2. 重载onMeasure()方法
为什么要重载onMeasure()方法这里就不赘述了,上一篇文章已经讲过,这里需要注意的是,自定义ViewGroup的onMeasure()方法中,除了计算自身的尺寸外,还需要调用measureChildren()函数来计算子控件的尺寸。
onMeasure()的定义不是本文的讨论重点,因此这里我直接使用默认的onMeasure()定义,当然measureChildren()是必须得加的。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
3. 实现onLayout()方法
onLayout()函数的原型如下:
//@param changed 该参数指出当前ViewGroup的尺寸或者位置是否发生了改变
//@param left top right bottom 当前ViewGroup相对于其父控件的坐标位置
protected void onLayout(boolean changed,int left, int top, int right, int bottom);
由于我们希望优先横向布局子控件,那么,首先,我们知道总宽度是多少,这个值可以通过getMeasuredWidth()来得到,当然子控件的宽度也可以通过子控件对象的getMeasuredWidth()来得到。
这样,就不复杂了,具体的实现代码如下所示:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int mViewGroupWidth = getMeasuredWidth(); //当前ViewGroup的总宽度
int mPainterPosX = left; //当前绘图光标横坐标位置
int mPainterPosY = top; //当前绘图光标纵坐标位置
int childCount = getChildCount();
for ( int i = 0; i < childCount; i++ ) {
View childView = getChildAt(i);
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
//如果剩余的空间不够,则移到下一行开始位置
if( mPainterPosX + width > mViewGroupWidth ) {
mPainterPosX = left;
mPainterPosY += height;
}
//执行ChildView的绘制
childView.layout(mPainterPosX,mPainterPosY,mPainterPosX+width, mPainterPosY+height);
//记录当前已经绘制到的横坐标位置
mPainterPosX += width;
}
}
4. 布局文件测试
下面我们就尝试写一个简单的xml文件,来测试一下我们的自定义ViewGroup,我们把子View的背景颜色都设置为黑色,方便我们辨识。
<com.titcktick.customview.CustomViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"> <View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/> <View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/> <View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/> <View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:background="@android:color/black"/> </com.titcktick.customview.CustomViewGroup>
5. 添加layout_margin
为了让核心逻辑更加清晰,上面的onLayout()实现我隐去了margin的计算,这样就会导致子控件的layout_margin不起效果,所以上述效果是子控件一个个紧挨着排列,中间没有空隙。那么,下面我们来研究下如何添加margin效果。
其实,如果要自定义ViewGroup支持子控件的layout_margin参数,则自定义的ViewGroup类必须重载 generateLayoutParams()函数,并且在该函数中返回一个ViewGroup.MarginLayoutParams派生类对象,这样 才能使用margin参数。
ViewGroup.MarginLayoutParams的定义关键部分如下,它记录了子控件的layout_margin值:
public static class MarginLayoutParams extends ViewGroup.LayoutParams {
public int leftMargin;
public int topMargin;
public int rightMargin;
public int bottomMargin;
}
你可以跟踪源码看看,其实XML文件中View的layout_xxx参数都是被传递到了各种自定义ViewGroup.LayoutParams派生类对象中。例如LinearLayout的LayoutParams定义的关键部分如下:
public class LinearLayout extends ViewGroup {
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
public float weight;
public int gravity = -1;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.LinearLayout_Layout);
weight = a.getFloat(com.android.internal.R.styleable.LinearLayout_Layout_layout_weight, 0);
gravity = a.getInt(com.android.internal.R.styleable.LinearLayout_Layout_layout_gravity, -1);
a.recycle();
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LinearLayout.LayoutParams(getContext(), attrs);
}
}
这样你大概就可以理解为什么LinearLayout的子控件支持weight和gravity的设置了吧,当然我们也可以这样自定义一些属于我们 ViewGroup特有的params,这里就不详细讨论了,我们只继承MarginLayoutParams来获取子控件的margin值。
public class CustomViewGroup extends ViewGroup {
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new CustomViewGroup.LayoutParams(getContext(), attrs);
}
}
这样修改之后,我们就可以在onLayout()函数中获取子控件的layout_margin值了,添加了layout_margin的onLayout()函数实现如下所示:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int mViewGroupWidth = getMeasuredWidth(); //当前ViewGroup的总宽度
int mViewGroupHeight = getMeasuredHeight(); //当前ViewGroup的总高度 int mPainterPosX = left; //当前绘图光标横坐标位置
int mPainterPosY = top; //当前绘图光标纵坐标位置 int childCount = getChildCount();
for ( int i = 0; i < childCount; i++ ) { View childView = getChildAt(i); int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight(); CustomViewGroup.LayoutParams margins = (CustomViewGroup.LayoutParams)(childView.getLayoutParams()); //ChildView占用的width = width+leftMargin+rightMargin
//ChildView占用的height = height+topMargin+bottomMargin
//如果剩余的空间不够,则移到下一行开始位置
if( mPainterPosX + width + margins.leftMargin + margins.rightMargin > mViewGroupWidth ) {
mPainterPosX = left;
mPainterPosY += height + margins.topMargin + margins.bottomMargin;
} //执行ChildView的绘制
childView.layout(mPainterPosX+margins.leftMargin, mPainterPosY+margins.topMargin,mPainterPosX+margins.leftMargin+width, mPainterPosY+margins.topMargin+height); mPainterPosX += width + margins.leftMargin + margins.rightMargin;
}
}
6. 总结
费了好大劲,终于算是把自定义ViewGroup的onLayout()相关知识点讲清楚了,如果有任何疑问欢迎留言或者来信lujun.hust@gmail.com交流.
[Android Pro] Android开发实践:自定义ViewGroup的onLayout()分析的更多相关文章
- [Android Pro] Android开发实践:为什么要继承onMeasure()
reference to : http://www.linuxidc.com/Linux/2014-12/110164.htm Android开 发中偶尔会用到自定义View,一般情况下,自定义Vie ...
- Android设置选项开发及自定义Preference样式
一个完整的Android应用程序都应该提供选项(或者叫偏好设置等等)让用户对APP的表现形式能够进行设置,比如说是否加入用户体验计划,或者是否自动升级.定时提醒.开启自启动.后台运行等等.提供一个好的 ...
- [Android Pro] Android 4.1 使用 Accessibility实现免Root自动批量安装功能
reference to : http://www.infoq.com/cn/articles/android-accessibility-installing?utm_campaign=info ...
- [Android Pro] Android 4.3 NotificationListenerService使用详解
reference to : http://blog.csdn.net/yihongyuelan/article/details/40977323 概况 Android在4.3的版本中(即API 18 ...
- [Android Pro] Android P版本 新功能介绍和兼容性处理(三)Android Studio 3.0 ~ 3.2 其他特性
cp : https://blog.csdn.net/yi_master/article/details/80067198 1:JAVA8特性支持 1)Base64.java 在升级到as3.0之后, ...
- [Android Pro] Android 性能分析工具dumpsys的使用
reference to : http://www.open-open.com/lib/view/open1405061994872.html Android提供的dumpsys工具可以用于查看感兴趣 ...
- [Android Pro] android 4.4 Android原生权限管理:AppOps
reference : http://m.blog.csdn.net/blog/langzxz/45308199 reference : http://blog.csdn.net/hyhyl1990/ ...
- [Android Pro] Android签名与认证详细分析之二(CERT.RSA剖析)
转载自: http://www.thinksaas.cn/group/topic/335449/ http://blog.csdn.net/u010571535/article/details/899 ...
- [Android Pro] android 杀死进程的方法
1: 杀死自己进程的方法 android.os.Process.killProcess(Process.myPid()); 2:杀死别人进程的方法(不能杀死自己) -------a: activity ...
随机推荐
- Sql的decimal、float、double类型的区别
三者的区别介绍 float:浮点型,含字节数为4,32bit,数值范围为-3.4E38~3.4E38(7个有效位) double:双精度实型,含字节数为8,64bit数值范围-1.7E308~1.7E ...
- HDU 1233 还是畅通工程(最小生成树)
传送门 还是畅通工程 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- Ubuntu学习总结-09 安装 Pycharm
一 下载 PyCharm 从以下网址下载Linux版本的Pycharm,这里使用的版本是pycharm-professional-2016.2.3.tar.gz . http://www.jetbra ...
- 彻底理解session
最详细的对session的解析: https://www.tooto.cc/archives/178
- C语言: 运算符,printf,scanf的用法
运算符/的运算结果和运算对象的数据类型有关,两个数都是in,则商就是int,取整数部分:被除数和除数中只要有一个或两个都是浮点型数据,则商也是浮点型,不去掉小数部分如:16/5 == 3:16/5.0 ...
- Hive metastore三种配置方式
http://blog.csdn.net/reesun/article/details/8556078 Hive的meta数据支持以下三种存储方式,其中两种属于本地存储,一种为远端存储.远端存储比较适 ...
- 思考JavaScript异常如何转为知识库?
线上 js 报错会变成一个邮件,发给前端开发 team,每个人自己认领.解决.其实这是一个不错的选择,也解决了最基本的问题:立即响应,修掉.不过也存在着一个问题,如何避免同样的错误?我的初步想法是这样 ...
- android 弹出AlertDialog的学习案例
我在编写的时候,测试的关键代码: AlertDialog.Builder builder=new AlertDialog.Builder(MainPointListActivity.this); bu ...
- MVC-命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Html”(是否缺少程序集引用?)
如上截图,明明引用了“System.web.mvc”,可是还出这样的错误. 解决方法: 1.右键引用的“System.Web.Mvc” 2.<复制本地>一样选择<True> 3 ...
- setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式
<script type="text/javascript"> setInterval(function(){ var myDate = new Date(); var ...