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
     
  • 相关阅读:
    PHP实现git部署的方法教程
    windows下php7.1安装redis扩展以及redis测试使用全过程
    win7下php7.1运行getenv('REMOTE_ADDR')fastcgi停止运行
    CGI与FastCGI
    Laravel 单设备登录
    Laravel 登录后清空COOKIE 方法
    PHP进阶与redis锁限制并发访问功能示例
    微信开放平台开发——网页微信扫码登录(OAuth2.0)
    laravel 项目本地版本为5.5,线上mysql 为5.7.21版本,执行严格模式
    mysql中bigint、int、mediumint、smallint与tinyint的取值范围
  • 原文地址:https://www.cnblogs.com/ttylinux/p/3948121.html
Copyright © 2011-2022 走看看