Android开发实践:自定义ViewGroup的onLayout()分析

简介:

Android开发中,对于自定义View,分为两种,一种是自定义控件(继承View类),另一种是自定义布局容器(继承ViewGroup)。如果是自定义控件,则一般需要重载两个方法,一个是onMeasure(),用来测量控件尺寸,另一个是onDraw(),用来绘制控件的UI。而自定义布局容器,则一般需要实现/重载三个方法,一个是onMeasure(),也是用来测量尺寸;一个是onLayout(),用来布局子控件;还有一个是dispatchDraw(),用来绘制UI。


本文主要分析自定义ViewGroup的onLayout()方法的实现。


ViewGroup类的onLayout()函数是abstract型,继承者必须实现,由于ViewGroup的定位就是一个容器,用来盛放子控件的,所以就必须定义要以什么的方式来盛放,比如LinearLayout就是以横向或者纵向顺序存放,而RelativeLayout则以相对位置来摆放子控件,同样,我们的自定义ViewGroup也必须给出我们期望的布局方式,而这个定义就通过onLayout()函数来实现。


我们通过实现一个水平优先布局的视图容器来更加深入地了解onLayout()的实现吧,效果如图所示(黑色方块为子控件,白色部分为自定义布局容器)。该容器的布局方式是,首先水平方向上摆放子控件,水平方向放不下了,则另起一行继续水平摆放。


wKiom1PzLDGz5ifsAABxoQ3CRhg847.jpg


    1.  自定义ViewGroup的派生类


    第一步,则是自定ViewGroup的派生类,继承默认的构造函数。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()是必须得加的。


1
2
3
4
5
@Override
protected  void  onMeasure( int  widthMeasureSpec,  int  heightMeasureSpec) {    
     super .onMeasure(widthMeasureSpec, heightMeasureSpec); 
     measureChildren(widthMeasureSpec, heightMeasureSpec);
}


    3.  实现onLayout()方法


    onLayout()函数的原型如下:


1
2
3
//@param changed 该参数指出当前ViewGroup的尺寸或者位置是否发生了改变
//@param left top right bottom 当前ViewGroup相对于其父控件的坐标位置
protected  void  onLayout( boolean  changed, int  left,  int  top,  int  right,  int  bottom);


    由于我们希望优先横向布局子控件,那么,首先,我们知道总宽度是多少,这个值可以通过getMeasuredWidth()来得到,当然子控件的宽度也可以通过子控件对象的getMeasuredWidth()来得到。


    这样,就不复杂了,具体的实现代码如下所示:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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的背景颜色都设置为黑色,方便我们辨识。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<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值:


1
2
3
4
5
6
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定义的关键部分如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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值。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()函数实现如下所示:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@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;
     }       
}


本文转自 Jhuster 51CTO博客,原文链接:http://blog.51cto.com/ticktick/1542200,如需转载请自行联系原作者

相关文章
|
17天前
|
XML Java Android开发
Android实现自定义进度条(源码+解析)
Android实现自定义进度条(源码+解析)
49 1
|
21天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
24天前
|
搜索推荐 Android开发 iOS开发
安卓与iOS系统的用户界面设计对比分析
本文通过对安卓和iOS两大操作系统的用户界面设计进行对比分析,探讨它们在设计理念、交互方式、视觉风格等方面的差异及各自特点,旨在帮助读者更好地理解和评估不同系统的用户体验。
18 1
|
26天前
|
调度 数据库 Android开发
构建高效Android应用:Kotlin协程的实践与优化
在Android开发领域,Kotlin以其简洁的语法和平台友好性成为了开发的首选语言。其中,Kotlin协程作为处理异步任务的强大工具,它通过提供轻量级的线程管理机制,使得开发者能够在不阻塞主线程的情况下执行后台任务,从而提升应用性能和用户体验。本文将深入探讨Kotlin协程的核心概念,并通过实例演示如何在实际的Android应用中有效地使用协程进行网络请求、数据库操作以及UI的流畅更新。同时,我们还将讨论协程的调试技巧和常见问题的解决方法,以帮助开发者避免常见的陷阱,构建更加健壮和高效的Android应用。
35 4
|
28天前
|
移动开发 Java Android开发
构建高效Android应用:Kotlin协程的实践之路
【2月更文挑战第31天】 在移动开发领域,性能优化和流畅的用户体验一直是开发者追求的目标。随着Kotlin语言的流行,其异步编程解决方案——协程(Coroutines),为Android应用带来了革命性的并发处理能力。本文将深入探讨Kotlin协程的核心概念、设计原理以及在Android应用中的实际应用案例,旨在帮助开发者掌握这一强大的工具,从而提升应用的性能和响应能力。
|
30天前
|
移动开发 调度 Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【2月更文挑战第30天】 在移动开发领域,尤其是针对Android平台,性能优化和应用流畅度始终是开发者关注的重点。近年来,Kotlin语言凭借其简洁性和功能性成为Android开发的热门选择。其中,Kotlin协程作为一种轻量级的线程管理解决方案,为异步编程提供了强大支持,使得编写非阻塞性代码变得更加容易。本文将深入分析Kotlin协程的核心优势,并通过实际案例展示如何有效利用协程提升Android应用的性能和响应速度。
|
18天前
|
Java Android开发 开发者
构建高效Android应用:Kotlin协程的实践与优化
在响应式编程范式日益盛行的今天,Kotlin协程作为一种轻量级的线程管理解决方案,为Android开发带来了性能和效率的双重提升。本文旨在探讨Kotlin协程的核心概念、实践方法及其在Android应用中的优化策略,帮助开发者构建更加流畅和高效的应用程序。通过深入分析协程的原理与应用场景,结合实际案例,本文将指导读者如何优雅地解决异步任务处理,避免阻塞UI线程,从而优化用户体验。
|
12天前
|
移动开发 API Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【4月更文挑战第7天】 在移动开发领域,性能优化和应用响应性的提升一直是开发者追求的目标。近年来,Kotlin语言因其简洁性和功能性在Android社区中受到青睐,特别是其对协程(Coroutines)的支持,为编写异步代码和处理并发任务提供了一种更加优雅的解决方案。本文将探讨Kotlin协程在Android开发中的应用,揭示其在提高应用性能和简化代码结构方面的潜在优势,并展示如何在实际项目中实现和优化协程。
|
12天前
|
XML 开发工具 Android开发
构建高效的安卓应用:使用Jetpack Compose优化UI开发
【4月更文挑战第7天】 随着Android开发不断进化,开发者面临着提高应用性能与简化UI构建流程的双重挑战。本文将探讨如何使用Jetpack Compose这一现代UI工具包来优化安卓应用的开发流程,并提升用户界面的流畅性与一致性。通过介绍Jetpack Compose的核心概念、与传统方法的区别以及实际集成步骤,我们旨在提供一种高效且可靠的解决方案,以帮助开发者构建响应迅速且用户体验优良的安卓应用。
|
15天前
|
Java Android开发
Android开发之使用OpenGL实现翻书动画
本文讲述了如何使用OpenGL实现更平滑、逼真的电子书翻页动画,以解决传统贝塞尔曲线方法存在的卡顿和阴影问题。作者分享了一个改造后的外国代码示例,提供了从前往后和从后往前的翻页效果动图。文章附带了`GlTurnActivity`的Java代码片段,展示如何加载和显示书籍图片。完整工程代码可在作者的GitHub找到:https://github.com/aqi00/note/tree/master/ExmOpenGL。
19 1
Android开发之使用OpenGL实现翻书动画