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,如需转载请自行联系原作者

相关文章
|
14天前
|
XML Java Android开发
Android实现自定义进度条(源码+解析)
Android实现自定义进度条(源码+解析)
47 1
|
18天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
21天前
|
搜索推荐 Android开发 iOS开发
安卓与iOS系统的用户界面设计对比分析
本文通过对安卓和iOS两大操作系统的用户界面设计进行对比分析,探讨它们在设计理念、交互方式、视觉风格等方面的差异及各自特点,旨在帮助读者更好地理解和评估不同系统的用户体验。
18 1
|
23天前
|
调度 数据库 Android开发
构建高效Android应用:Kotlin协程的实践与优化
在Android开发领域,Kotlin以其简洁的语法和平台友好性成为了开发的首选语言。其中,Kotlin协程作为处理异步任务的强大工具,它通过提供轻量级的线程管理机制,使得开发者能够在不阻塞主线程的情况下执行后台任务,从而提升应用性能和用户体验。本文将深入探讨Kotlin协程的核心概念,并通过实例演示如何在实际的Android应用中有效地使用协程进行网络请求、数据库操作以及UI的流畅更新。同时,我们还将讨论协程的调试技巧和常见问题的解决方法,以帮助开发者避免常见的陷阱,构建更加健壮和高效的Android应用。
31 4
|
25天前
|
移动开发 Java Android开发
构建高效Android应用:Kotlin协程的实践之路
【2月更文挑战第31天】 在移动开发领域,性能优化和流畅的用户体验一直是开发者追求的目标。随着Kotlin语言的流行,其异步编程解决方案——协程(Coroutines),为Android应用带来了革命性的并发处理能力。本文将深入探讨Kotlin协程的核心概念、设计原理以及在Android应用中的实际应用案例,旨在帮助开发者掌握这一强大的工具,从而提升应用的性能和响应能力。
|
26天前
|
移动开发 调度 Android开发
构建高效Android应用:探究Kotlin协程的优势与实践
【2月更文挑战第30天】 在移动开发领域,尤其是针对Android平台,性能优化和应用流畅度始终是开发者关注的重点。近年来,Kotlin语言凭借其简洁性和功能性成为Android开发的热门选择。其中,Kotlin协程作为一种轻量级的线程管理解决方案,为异步编程提供了强大支持,使得编写非阻塞性代码变得更加容易。本文将深入分析Kotlin协程的核心优势,并通过实际案例展示如何有效利用协程提升Android应用的性能和响应速度。
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
92 0
|
1月前
|
数据库 Android开发 开发者
构建高性能微服务架构:从理论到实践构建高效Android应用:探究Kotlin协程的优势
【2月更文挑战第16天】 在当今快速迭代和竞争激烈的软件市场中,微服务架构以其灵活性、可扩展性和独立部署能力而受到企业的青睐。本文将深入探讨如何构建一个高性能的微服务系统,涵盖从理论基础到具体实现的各个方面。我们将重点讨论服务拆分策略、通信机制、数据一致性以及性能优化等关键主题,为读者提供一个清晰、实用的指南,以便在复杂多变的业务环境中构建和维护健壮的微服务体系结构。 【2月更文挑战第16天】 在移动开发领域,性能优化和流畅的用户体验是至关重要的。随着技术的不断进步,Kotlin作为一种现代编程语言,在Android开发中被广泛采用,尤其是其协程特性为异步编程带来了革命性的改进。本文旨在深入
238 5
|
1月前
|
设计模式 人工智能 开发工具
安卓应用开发:构建未来移动体验
【2月更文挑战第17天】 随着智能手机的普及和移动互联网技术的不断进步,安卓应用开发已成为一个热门领域。本文将深入探讨安卓平台的应用开发流程、关键技术以及未来发展趋势。通过分析安卓系统的架构、开发工具和框架,本文旨在为开发者提供全面的技术指导,帮助他们构建高效、创新的移动应用,以满足不断变化的市场需求。
18 1
|
15天前
|
Java Android开发 开发者
构建高效Android应用:Kotlin协程的实践与优化
在响应式编程范式日益盛行的今天,Kotlin协程作为一种轻量级的线程管理解决方案,为Android开发带来了性能和效率的双重提升。本文旨在探讨Kotlin协程的核心概念、实践方法及其在Android应用中的优化策略,帮助开发者构建更加流畅和高效的应用程序。通过深入分析协程的原理与应用场景,结合实际案例,本文将指导读者如何优雅地解决异步任务处理,避免阻塞UI线程,从而优化用户体验。