主目錄見(jiàn):Android高級(jí)進(jìn)階知識(shí)(這是總目錄索引)
這一篇主要是自定義ViewGroup的第一篇跪帝,所以會(huì)選一個(gè)簡(jiǎn)單的例子進(jìn)行知識(shí)點(diǎn)的說(shuō)明泣特,看過(guò)前面的文章或者已經(jīng)會(huì)了前面的知識(shí)逆皮,這一篇應(yīng)該不是問(wèn)題胁镐,我們就直接開(kāi)始自定義ViewGroup之旅吧(ps:后面的例子還在尋找只估,暫未找到比較典型的例子臼氨,如果有什么好的可以推薦)。首先曬出我們今天的例子:
一.目標(biāo)
因?yàn)檫@篇是對(duì)上面一篇《View和ViewGroup的繪制原理源碼分析》知識(shí)點(diǎn)的回顧芭届。所以我們的目標(biāo)很明確:
1.練習(xí)自定義ViewGroup怎么測(cè)量,布局储矩,包括怎么繪制。
2.了解自定義ViewGroup實(shí)現(xiàn)的幾個(gè)構(gòu)造函數(shù)作用褂乍。
3.了解自定義屬性持隧。
二.自定義ViewGroup
1.構(gòu)造函數(shù)
我們知道,自定義ViewGroup會(huì)讓實(shí)現(xiàn)構(gòu)造函數(shù)逃片,那么這幾個(gè)構(gòu)造函數(shù)都是干嘛的呢屡拨?首先我們說(shuō)下這三個(gè)構(gòu)造函數(shù)是什么情況下會(huì)被調(diào)用:
?1.public CardLayout(Context context) {}一個(gè)參數(shù)的構(gòu)造函數(shù)的作用是程序內(nèi)實(shí)例化該控件時(shí)調(diào)用。
?2.public CardLayout(Context context, AttributeSet attrs) {}兩個(gè)參數(shù)的構(gòu)造函數(shù)的作用是Layout文件實(shí)例化,會(huì)把xml里面的參數(shù)通過(guò)AttributeSet傳進(jìn)構(gòu)造函數(shù)里面呀狼。
?3.public CardLayout(Context context, AttributeSet attrs, int defStyleAttr) {}三個(gè)參數(shù)的構(gòu)造函數(shù)的第三個(gè)參數(shù)是可以攜帶一個(gè)主題的style信息裂允。
那么我們平常寫(xiě)是要怎么寫(xiě)呢?如果是直接繼承的ViewGroup的話哥艇,建議是這么寫(xiě):
public CardLayout(Context context) {
this(context,null);
}
public CardLayout(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public CardLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CardLayout);
horizontalSpace = a.getDimensionPixelOffset(R.styleable.CardLayout_horizontal_space,DEFAULT_HORIZONTAL_SPACE);
verticalSpace = a.getDimensionPixelOffset(R.styleable.CardLayout_vertical_space,DEFAULT_VERTICAL_PACE);
a.recycle();
}
一個(gè)參數(shù)的構(gòu)造函數(shù)調(diào)用兩個(gè)參數(shù)的構(gòu)造函數(shù)绝编,兩個(gè)參數(shù)的構(gòu)造函數(shù)調(diào)用三個(gè)參數(shù)的構(gòu)造函數(shù)。但是如果你是繼承的已有的控件如ListView貌踏,TextView等十饥,那么我們建議用下面這種方式寫(xiě):
public CardLayout(Context context) {
super(context);
init(context,null)
}
public CardLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CardLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs){
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CardLayout);
horizontalSpace = a.getDimensionPixelOffset(R.styleable.CardLayout_horizontal_space,DEFAULT_HORIZONTAL_SPACE);
verticalSpace = a.getDimensionPixelOffset(R.styleable.CardLayout_vertical_space,DEFAULT_VERTICAL_PACE);
a.recycle();
}
為什么呢?這是因?yàn)長(zhǎng)istView祖乳,TextView內(nèi)部構(gòu)造函數(shù)會(huì)有一個(gè)默認(rèn)的defStyleAttr逗堵,如果采用第一種方式寫(xiě)的話那么有可能會(huì)丟失這個(gè)defStyleAttr(因?yàn)閮蓚€(gè)參數(shù)的構(gòu)造函數(shù)調(diào)用三個(gè)參數(shù)的構(gòu)造函數(shù)的時(shí)候傳進(jìn)去的是零)。
2.自定義屬性
自定義屬性雖然比較簡(jiǎn)單眷昆,但是是大部分自定義ViewGroup必經(jīng)的一部蜒秤,如果想要詳細(xì)了解自定義屬性這里推薦一篇《Android 深入理解Android中的自定義屬性 》,這篇講的非常詳細(xì)了。這里我們簡(jiǎn)單地定義:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CardLayout">
<attr name="horizontal_space" format="dimension"></attr>
<attr name="vertical_space" format="dimension"></attr>
</declare-styleable>
</resources>
這個(gè)例子的水平間隔和垂直間隔是可以用戶自定義的隙赁,因?yàn)樗麄兪莇p單位的垦藏,所以format="dimension"。
3.onMeasure
我們從上一篇《View和ViewGroup的繪制原理源碼分析》知道伞访,測(cè)量的時(shí)候會(huì)調(diào)用到ViewGroup的onMeasure方法掂骏,這個(gè)方法不是final的,我們可以重寫(xiě)厚掷。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width = 0;
int height = 0;
// measureChildren(widthMeasureSpec,heightMeasureSpec);
for (int i = 0; i < getChildCount();i++){
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
LayoutParams lp = child.getLayoutParams();
int childWidthSpec = getChildMeasureSpec(widthMeasureSpec,child.getPaddingLeft() + child.getPaddingRight() ,lp.width);
int childHeightSpec = getChildMeasureSpec(heightMeasureSpec,child.getPaddingTop() + child.getPaddingBottom(),lp.height);
child.measure(childWidthSpec,childHeightSpec);
width = Math.max(width,i * horizontalSpace + child.getMeasuredWidth());
height = Math.max(height,i * verticalSpace + child.getMeasuredHeight());
}
}
setMeasuredDimension(MeasureSpec.EXACTLY == widthMode ? widthSize : width,
MeasureSpec.EXACTLY == heightMode ? heightSize : height);
}
首先我們看到第一個(gè)部分:
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
這個(gè)地方是獲取ViewGroup推薦的計(jì)算寬和高以及相應(yīng)的模式即父類測(cè)量完推薦該自定義控件的寬高弟灼,什么意思呢?我們首先應(yīng)該知道我們的模式有三種:
1.EXACTLY(精確模式):父容器能夠計(jì)算出自己的大小冒黑,一般是設(shè)置為match_parent或者固定值的自定義控件田绑。
2.AT_MOST(至多不超過(guò)模式):父容器指定了一個(gè)大小, View 的大小不能大于這個(gè)值抡爹,也就是父容器不能夠直接計(jì)算出自己的大小掩驱,需要先由它所有的子View自己去計(jì)算一下自己大朽诹选(measureChildren())汹来,然后再去設(shè)置該自定義控件自己的大小(setMeasuredDimension)。一般是設(shè)置為wrap_content糊余。
3.UNSPECIFIED(不確定模式):父容器不對(duì) view 有任何限制泵殴,要多大給多大涮帘,多見(jiàn)于ListView、GridView等笑诅。
我們這里的widthMeasureSpec或者h(yuǎn)eightMeasureSpec其實(shí)是mode+size的32位數(shù)调缨,高兩位為mode疮鲫,后面30位為size的值即控件的寬或者高。如果我們View要自己手動(dòng)合成widthMeasureSpec或者h(yuǎn)eightMeasureSpec我們可以調(diào)用makeMeasureSpec方法弦叶,具體實(shí)現(xiàn)如下:
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
所以我們這里得到父控件給我們測(cè)量的寬高和模式俊犯。然后我們繼續(xù)看代碼:
for (int i = 0; i < getChildCount();i++){
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
LayoutParams lp = child.getLayoutParams();
int childWidthSpec = getChildMeasureSpec(widthMeasureSpec,child.getPaddingLeft() + child.getPaddingRight() ,lp.width);
int childHeightSpec = getChildMeasureSpec(heightMeasureSpec,child.getPaddingTop() + child.getPaddingBottom(),lp.height);
child.measure(childWidthSpec,childHeightSpec);
width = Math.max(width,i * horizontalSpace + child.getMeasuredWidth());
height = Math.max(height,i * verticalSpace + child.getMeasuredHeight());
}
}
我們看到我們這里會(huì)遍歷出來(lái)所有的子View,因?yàn)閂iewGroup下面會(huì)有多個(gè)View湾蔓,所以這個(gè)地方我們遍歷出來(lái)分別測(cè)量瘫析,首先我們判斷一下View是不是設(shè)置了visibility="gone"如果設(shè)置了那就不會(huì)測(cè)量了,不然就先調(diào)用getChildMeasureSpec()方法默责,這個(gè)方法是根據(jù)子View的padding和width以及父類給的widthMeasureSpec來(lái)獲得子類的childWidthSpec(子view的mode+size值)贬循,高度跟寬度類似,然后調(diào)用child.measure(childWidthSpec,childHeightSpec)方法進(jìn)行測(cè)量子視圖桃序。ViewGroup還提供了簡(jiǎn)單的測(cè)量子視圖的方法:measureChildren杖虾,measureChildWithMargins具體里面做了什么跟我們上面寫(xiě)的代碼有點(diǎn)像。接著我們看最后一句:
setMeasuredDimension(MeasureSpec.EXACTLY == widthMode ? widthSize : width,
MeasureSpec.EXACTLY == heightMode ? heightSize : height);
這個(gè)地方我們看到我們判斷了widthMode媒熊,heightMode看是哪一種方式奇适,如果是EXACTLY說(shuō)明父容器能測(cè)量出來(lái)我們的寬高即自定義控件layout_xxx設(shè)置了match_parent或者是精確值,我們就把父容器給我們的寬高設(shè)置給我們的自定義控件即可芦鳍。如果我們的模式是AT_MOST或者UNSPECIFIED嚷往,其實(shí)UNSPECIFIED的場(chǎng)景比較少,主要是考慮AT_MOST即wrap_content的情況柠衅,wrap_content的情況我們父容器不知道我們自定義控件的寬高皮仁,我們需要根據(jù)自定義控件的子View的寬高然后來(lái)判斷自定義控件的寬高。
4.onLayout
這個(gè)方法主要是布局自定義控件中子view的位置菲宴。我們這個(gè)自定義控件的布局代碼如下:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed){
for (int i = 0;i < getChildCount();i++){
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int leftSpace = horizontalSpace * i;
int topSpace = verticalSpace * i;
child.layout(leftSpace,topSpace,leftSpace + child.getMeasuredWidth(),topSpace + child.getMeasuredHeight());
}
}
}
}
我們看到我們這邊是遍歷自定義控件下面所有子view贷祈,然后分別調(diào)用child.layout()方法,這個(gè)方法里面的參數(shù)主要是左喝峦,上势誊,右,下四個(gè)值谣蠢,即左上角和右下角的坐標(biāo)值粟耻。
5.自定義LayoutParams
除了上面的兩個(gè)主要方法,我們有時(shí)還會(huì)自定義LayoutParams眉踱,我們會(huì)override下面幾個(gè)方法:
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new CustomLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new CustomLayoutParams(getContext(),attrs);
}
@Override
protected LayoutParams generateLayoutParams(LayoutParams p) {
return new CustomLayoutParams(p.width,p.height);
}
@Override
protected boolean checkLayoutParams(LayoutParams p) {
return p instanceof CustomLayoutParams;
}
我們看到這幾個(gè)是要實(shí)現(xiàn)的方法勋颖,generateDefaultLayoutParams(),generateLayoutParams(),generateLayoutParams()方法主要是返回默認(rèn)的LayoutParams和自定義的LayoutParams勋锤,checkLayoutParams()這個(gè)方法主要是檢查下是否是我們自定義的LayoutParams。那么這個(gè)LayoutParams到底怎么自定義呢侥祭?首先我們要自定義一個(gè)屬性:
<declare-styleable name="CardLayout_LayoutParams">
<attr name="vertical_spacing" format="dimension"/>
</declare-styleable>
然后我們要繼承ViewGroup.LayoutParams類實(shí)現(xiàn):
public static class CustomLayoutParams extends ViewGroup.LayoutParams{
private int verSpacing;
public CustomLayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CardLayout_LayoutParams);
try {
verSpacing = a.getDimensionPixelSize(R.styleable.CardLayout_vertical_space,-1);
} finally {
a.recycle();
}
}
public CustomLayoutParams(int width, int height) {
super(width, height);
}
}
我們可以看到我們這里面自定義了一個(gè)屬性verSpacing叁执。那么我們到底要怎么使用這個(gè)自定義的LayoutParams呢茄厘?在布局里面我們可以修改成下面這樣:
<TextView
android:layout_width="200dp"
android:layout_height="200dp"
android:text="第二張卡牌"
app:vertical_spacing="100dp"
android:padding="25dp"
android:background="@color/colorAccent"/>
這里面我們看到跟自定義屬性用法一樣 app:vertical_spacing="100dp",然后我們修改onMeasure的測(cè)量方法:
for (int i = 0; i < getChildCount();i++){
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
CustomLayoutParams lp = (CustomLayoutParams) child.getLayoutParams();
int childWidthSpec = getChildMeasureSpec(widthMeasureSpec,child.getPaddingLeft() + child.getPaddingRight(),lp.width);
int childHeightSpec = getChildMeasureSpec(heightMeasureSpec,child.getPaddingTop() + child.getPaddingBottom(),lp.height);
child.measure(childWidthSpec,childHeightSpec);
width = Math.max(width,i * horizontalSpace + child.getMeasuredWidth());
if (lp.verSpacing != -1 && i >= 1){
height = Math.max(height,lp.verSpacing + (i-1)*verticalSpace + child.getMeasuredHeight());
}else{
height = Math.max(height,i * verticalSpace + child.getMeasuredHeight());
}
}
}
我們看到我們會(huì)獲取到每個(gè)子view的CustomLayoutParams 谈宛,然后獲取這個(gè)屬性verSpacing 的值次哈,然后就可以進(jìn)行使用了。我們的onLayout也要修改:
for (int i = 0;i < getChildCount();i++){
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
CustomLayoutParams lp = (CustomLayoutParams) child.getLayoutParams();
int leftSpace = horizontalSpace * i;
int topSpace = verticalSpace * i;
if (lp.verSpacing != -1 && i >= 1){
topSpace = lp.verSpacing + (i-1)*verticalSpace;
}
child.layout(leftSpace,topSpace,leftSpace + child.getMeasuredWidth(),topSpace + child.getMeasuredHeight());
}
}
在布局的時(shí)候我們添加進(jìn)這個(gè)CustomLayoutParams 里面這個(gè)verSpacing 的影響吆录。所以我們最后的效果變成了這樣:
到這里我們大概自定義的ViewGroup已經(jīng)講解完畢窑滞,但是不是還有onDraw方法呢?為什么這里沒(méi)有了恢筝,其實(shí)onDraw方法ViewGroup是默認(rèn)不調(diào)用的哀卫,因?yàn)檫@個(gè)方法是繪制的子View,只有在有背景或者設(shè)置了setWillNotDraw(false)的情況下才會(huì)調(diào)用撬槽,但是自定義ViewGroup會(huì)調(diào)用dispatchDraw方法此改,這個(gè)方法是繪制ViewGroup下面的子View,但是這個(gè)方法一般很少使用侄柔。所以這里我們的自定義ViewGroup講到這里已經(jīng)完畢共啃。
如果你想要這篇文檔的源代碼。那么請(qǐng)[重?fù)粝螺d]源代碼暂题。
總結(jié):這是我們自定義ViewGroup的第一個(gè)實(shí)例移剪,后面我們希望能有復(fù)雜點(diǎn)但是典型的例子,如果你有什么推薦薪者,可以留言哈纵苛,一起把知識(shí)說(shuō)明完整哈。