onLayout()方法用于指定布局中子控件的位置,该方法通常在自定义的ViewGroup容器中重写。
重写onLayout()方法中的常用方法:
getChildCount() 获取子控件数量
getChildAt( int index ) 获取指定index的子控件,返回View
view.getVisibility() 获取控件存在状态,GONE,TRUE,FALSE
view.getMeasuredHeight() 获取控件高度px
view.getMeasuredWidth() 获取控件宽度px
view.layout( int l , int t , int r , int b ) 设置控件四周边界与父容器左和上距离,左与父左,上与父上,右与父左,下与父上。
//例
protected void onLayout(boolean changed, int l, int t, int r, int b) {for (int i=0;i< getChildCount() ;i++){View view= getChildAt(i) ;if( view.getVisibility() !=GONE){int width= view.getMeasuredWidth() ;int height= view.getMeasuredHeight();//重设子控件布局位置view.layout(~,~,~,~);}}
}
在其他方法中使用requestLayout()会再次调用onLayout()重定义布局。