android自定义的生命周期,android 自定义控件之ViewGroup生命周期执行步骤(示例代码)...
前言
了解ViewGroup的生命周期的執(zhí)行步驟對于自己自定義ViewGroup的時候十分重要,清楚了整個流程才能對ViewGroup有更深的理解。本文從個人的總結,來闡述一下執(zhí)行的順序。
執(zhí)行說明
首先ViewGroup的常用的生命周期主要有:構造方法、onLayout()、onFinishInflate()、onMeasure()、onSizeChanged(),前兩種在創(chuàng)建ViewGroup子類的時候,必須重寫。至于draw()和drawChild()是其用來繪制背景和子View用的,就不在生命周期里一一敘述。
第一種:在xml里直接引用的,執(zhí)行順序一般是:構造方法->onFinishInflate()(只執(zhí)行一次)->onMeasure()(可能多次執(zhí)行)->onSizeChanged()(在重新onMeasure的時候發(fā)現(xiàn)跟之前測量的尺寸不一樣的時候就會回調此方法)->onLayout()(布置子View)->onMeasure()->onLayout().......
第二種:在Activity中setContentView( newCustomView(this))引用的,執(zhí)行順序與第一種相比,除了構造方法引用的不一致和不執(zhí)行onFinishInflate()外,其他基本一致。
第三種:在Activity中直接new CustomView(this)而且不添加任何父布局的時候只會執(zhí)行構造方法,其它不會執(zhí)行。
總結技巧:
onMeasure()里一般是定義子控件的測量尺寸和寬高。
首先設置ViewGroup自身的尺寸如下:
int?widthSize?=?MeasureSpec.getSize(widthMeasureSpec);
int?heightSize?=?MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize,?heightSize);
然后設置子View的尺寸例如下面:
View?leftMenuView?=?getChildAt(1);
MarginLayoutParams?lp?=?(MarginLayoutParams)
leftMenuView.getLayoutParams();
final?int?drawerWidthSpec?=?getChildMeasureSpec(widthMeasureSpec,
mMinDrawerMargin?+?lp.leftMargin?+?lp.rightMargin,
lp.width);
final?int?drawerHeightSpec?=?getChildMeasureSpec(heightMeasureSpec,
lp.topMargin?+?lp.bottomMargin,
lp.height);
leftMenuView.measure(drawerWidthSpec,?drawerHeightSpec);
View?contentView?=?getChildAt(0);
lp?=?(MarginLayoutParams)?contentView.getLayoutParams();
final?int?contentWidthSpec?=?MeasureSpec.makeMeasureSpec(
widthSize?-?lp.leftMargin?-?lp.rightMargin,?MeasureSpec.EXACTLY);
final?int?contentHeightSpec?=?MeasureSpec.makeMeasureSpec(
heightSize?-?lp.topMargin?-?lp.bottomMargin,?MeasureSpec.EXACTLY);
contentView.measure(contentWidthSpec,?contentHeightSpec);
int getChildMeasureSpec(int spec,int padding,int childDimension) 返回的是測量尺寸規(guī)格spec,可以給子View設置padding,不需要設置padding就直接如contentView一樣。
onLayout()布局子view的位置,基本上用到layout(left,top,right,bottom);
getWidth()和getMeasureWidth()的區(qū)別與聯(lián)系:
getMeasuredWidth(): 只要一執(zhí)行完 setMeasuredDimension() 方法,就有值了,并且不再改變。簡單來說執(zhí)行完onMeasure里的方法后就可以獲取;
getWidth()只有在執(zhí)行onMeasure()之后才能獲取,但是可能應為布局大小調整發(fā)生變化,如果onLayout()沒有對子View的寬高進行修改,那么兩個值相等。
生命周期表:
總結
以上是生活随笔為你收集整理的android自定义的生命周期,android 自定义控件之ViewGroup生命周期执行步骤(示例代码)...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea项目启动不起来_这些教育创业项目
- 下一篇: CMOS详解