zoukankan      html  css  js  c++  java
  • 自定义ViewGroup

    定义一个自定义View组件,如果只是关注这个View的外观和大小,那么,要重写onDraw,onMeasure这两个方法。比如,我自定义了一个LabelView
     
    自定义完View之后,该View就可以像TextView之类的在一个ViewGroup中被使用了。
     
    ViewGroup中,会对存放在它其中的子View(childView)进行摆放。常见的ViewGroup有LinearLayout,RelativeLayout,FrameLayout。
    那么,如果要实现一个自定义的ViewGroup呢?
     
    实现自定义一个ViewGroup时,可以继承LinearLayout或者RelativeLayout等现有的ViewGroup。也可以直接继承类ViewGroup。
     
    在实现自定义ViewGroup时,要重写onLayout。系统回调你自己实现的onLayout的目的,即执行其中实现布局的代码。
     
    例如:系统会回调该方法,来执行该ViewGroup对其中的childView的布局。系统执行下述onLayout中的布局代码后,
    达到的布局效果如下图:
            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                   // TODO Auto-generated method stub
                   int childCount = getChildCount() ;        
                   int startLeft = 0 ;//设置每个子View的起始横坐标  
                   int startTop = 10 ; //每个子View距离父视图的位置 , 简单设置为10px吧 。 可以理解为 android:margin=10px ;        
                   Log. v(TAG, "------- onLayout start ") ; 
                   for(int i=0 ;i<childCount ; i++){ 
                          View child = getChildAt(i) ;   //获得每个对象的引用 
                          child.layout(startLeft, startTop, startLeft+child.getMeasuredWidth(), startTop+ child.getMeasuredHeight()) ; 
                          startLeft =startLeft+ child.getMeasuredWidth() + 10;  //校准startLeft值,View之间的间距设为10px ; 
                          Log. v(TAG, "------- onLayout startLeft " +startLeft) ; 
                   }            
     
           }
     
    参考资料:

    public void layout (int l, int t, int r, int b)

    Added in API level 1

    Assign a size and position to a view and all of its descendants(子节点)

    This is the second phase of the layout mechanism. (The first is measuring). In this phase, each parent calls layout on all of its children to position them. This is typically done using the child measurements that were stored in the measure pass().

    Derived classes should not override this method. Derived classes with children should override onLayout. In that method, they should call layout on each of their children.

    Parameters
    l Left position, relative to parent
    t Top position, relative to parent
    r Right position, relative to parent
    b Bottom position, relative to parent
     
    http://blog.csdn.net/androiddevelop/article/details/8108970
    http://blog.csdn.net/aaa2832/article/details/7849400
    http://blog.csdn.net/aaa2832/article/details/7844904
     
  • 相关阅读:
    RTP 与RTCP 解释. 含同步时间戳
    Linux命令之ar
    函数参数的传递问题(指针的指针)
    传指针和传指针引用的区别/指针和引用的区别(本质)
    gdb optimized out错误解决
    实时视频应用之QoS关键技术分析
    中国大陆地区桌面操作系统占比
    一句命令查询 当前目录下面不同文件前缀的数量 并且进行排序
    一致性哈希算法和Go语言实现
    频率之外谁重要?计算机存储系统解析(转载)
  • 原文地址:https://www.cnblogs.com/ttylinux/p/3948121.html
Copyright © 2011-2022 走看看