通過上一節的講解呢我們大致對Android測量控件有個初步的了解,而此后呢也有不少盆友Q小窗我問了不少問題,不過其實這些問題大多都不是問題,至于到底是不是問題呢,還要等我研究下究竟可不可以把這些問題歸為問題……稍等、我吃個藥先。大多數盆友的反應是在對控件測量的具體方法還不是很了解,不過不要著急,上一節的內容就當飯前甜點,接下來我們會用一個例子來說明這一切不是問題的問題,這個例子中的控件呢我稱其為SquareLayout,意為方形布局(注:該例子僅作演示,實際應用意義并不大),我們將置于該布局下的所有子元素都強制變為一個正方形~~說起簡單,但是如我上一節所說控件的設計要盡可能考慮到所有的可能性才能趨于完美~~但是沒有絕對的完美……在5/12時我曾說過不要將自己當作一個coder而要把自己看成一個designer,控件是我們設計出來的而不是敲出來的,在我們code之前就該對這個控件有一個較為perfect的design,考慮到控件的屬性設計、行為設計、交互設計等等,這里呢我也對我們的SquareLayout做了一個簡單的設計:

非常簡單,如上我們所說,SquareLayout內部的子元素都會以正方形的形狀顯示,我們可以給其定義一個orientation屬性來表示子元素排列方式,如上是orientation為橫向時的排列方式,而下面則是縱向的排列方式:

指定了排列方式后我們的子元素就會以此為基準排列下去,但是如果子元素超出了父容器的區域怎么辦呢?這時我們可以指定兩種處理方式:一、不管,任由子元素被父容器的邊距裁剪;二、強制被裁剪的子元素舍棄其原有布局重新布局。暫時我們先默認第一種吧。接著看,如果我們的子元素只能是橫著一排或豎著一排著實單調,我們可以考慮定義兩個屬性控制其最大排列個數,比如縱向排列時,我們可以指定一個max_row屬性,當排列的行數超過該值時自動換列:

當然我們也可以在子元素橫向排列時為其指定max_column屬性,當橫向排列列數超過該值時自動換行:

仔細想想,當max_column為1時,我們的排列方式其實就是縱向的而當max_row為1時就是橫向的,那么我們的orientation屬性豈不是成了擺設?會不會呢?留給各位去想。好吧、暫時就先定義這倆屬性,光這倆已經夠折騰的了,來來來創建我們的布局:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private int mMaxRow;// 最大行數
private int mMaxColumn;// 最大列數
private int mOrientation;// 排列方向
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
~~~
上一節我們曾說過,要讓我們父容器下子元素的margins外邊距能夠被正確計算,我們必需重寫父容器的三個相關方法并返回一個MarginLayoutParams的子類:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去各種蛋疼的成員變量…………
// 省去構造方法…………
// 省去onLayout方法…………
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {
return new MarginLayoutParams(p);
}
@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
}
~~~
這里我直接返回一個MarginLayoutParams的實例對象,因為我不需要在LayoutParams處理自己的邏輯,單純地計算margins就沒必要去實現一個自定義的MarginLayoutParams子類了,除此之外,你還可以重寫checkLayoutParams方法去驗證當前所使用的LayoutParams對象是否MarginLayoutParams的一個實例:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去各種蛋疼的成員變量…………
// 省去構造方法…………
// 省去onLayout方法…………
// 省去三個屌毛方法……
@Override
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
return p instanceof MarginLayoutParams;
}
}
~~~
然后呢我們就要開始對控件進行測量了,首先重寫onMeasure方法是肯定的,那么我們就先在onMeasure中先把測量的邏輯處理了先,不過我們還是按部就班一步一步來,先把排列方式搞定:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量標識值
private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默認值
private int mMaxRow = DEFAULT_MAX_ROW;// 最大行數
private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列數
private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默認橫向
// 省去構造方法…………
@SuppressLint("NewApi")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/*
* 聲明臨時變量存儲父容器的期望值
* 該值應該等于父容器的內邊距加上所有子元素的測量寬高和外邊距
*/
int parentDesireWidth = 0;
int parentDesireHeight = 0;
// 聲明臨時變量存儲子元素的測量狀態
int childMeasureState = 0;
/*
* 如果父容器內有子元素
*/
if (getChildCount() > 0) {
/*
* 那么就遍歷子元素
*/
for (int i = 0; i < getChildCount(); i++) {
// 獲取對應遍歷下標的子元素
View child = getChildAt(i);
/*
* 如果該子元素沒有以“不占用空間”的方式隱藏則表示其需要被測量計算
*/
if (child.getVisibility() != View.GONE) {
// 測量子元素并考量其外邊距
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
// 比較子元素測量寬高并比較取其較大值
int childMeasureSize = Math.max(child.getMeasuredWidth(), child.getMeasuredHeight());
// 重新封裝子元素測量規格
int childMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasureSize, MeasureSpec.EXACTLY);
// 重新測量子元素
child.measure(childMeasureSpec, childMeasureSpec);
// 獲取子元素布局參數
MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
/*
* 考量外邊距計算子元素實際寬高
*/
int childActualWidth = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;
int childActualHeight = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
// 累加子元素的實際寬度
parentDesireWidth += childActualWidth;
// 獲取子元素中高度最大值
parentDesireHeight = Math.max(parentDesireHeight, childActualHeight);
}
/*
* 如果為豎向排列
*/
else if (mOrientation == ORIENTATION_VERTICAL) {
// 累加子元素的實際高度
parentDesireHeight += childActualHeight;
// 獲取子元素中寬度最大值
parentDesireWidth = Math.max(parentDesireWidth, childActualWidth);
}
// 合并子元素的測量狀態
childMeasureState = combineMeasuredStates(childMeasureState, child.getMeasuredState());
}
}
/*
* 考量父容器內邊距將其累加到期望值
*/
parentDesireWidth += getPaddingLeft() + getPaddingRight();
parentDesireHeight += getPaddingTop() + getPaddingBottom();
/*
* 嘗試比較父容器期望值與Android建議的最小值大小并取較大值
*/
parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());
parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());
}
// 確定父容器的測量寬高
setMeasuredDimension(resolveSizeAndState(parentDesireWidth, widthMeasureSpec, childMeasureState),
resolveSizeAndState(parentDesireHeight, heightMeasureSpec, childMeasureState << MEASURED_HEIGHT_STATE_SHIFT));
}
// 省去onLayout方法…………
// 省去四個屌毛方法……
}
~~~
上面代碼注釋很清楚,具體的我就不扯了,小窗我的童鞋有一部分問過我上一節中我在確定測量尺寸時候使用的resolveSize方法作用(以下代碼源自上一節的CustomLayout):
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/15
*
*/
public class CustomLayout extends ViewGroup {
// 省去N多代碼
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 省省省………………
// 設置最終測量值
setMeasuredDimension(resolveSize(parentDesireWidth, widthMeasureSpec), resolveSize(parentDesireHeight, heightMeasureSpec));
}
// 省去N+1多代碼
}
~~~
那么這個resolveSize方法其實是View提供給我們解算尺寸大小的一個工具方法,其具體實現在API 11后交由另一個方法resolveSizeAndState也就是我們這一節例子所用到的去處理:
~~~
public static int resolveSize(int size, int measureSpec) {
return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
}
~~~
而這個resolveSizeAndState方法具體實現其實跟我們上一節開頭解算Bitmap尺寸的邏輯類似:
~~~
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
if (specSize < size) {
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result | (childMeasuredState&MEASURED_STATE_MASK);
}
~~~
是不是很類似呢?如果沒看過我上一節的內容,可以回頭去閱讀一下自定義控件其實很簡單7/12,與我們不同的是這個方法多了一個childMeasuredState參數,而上面例子我們在具體測量時也引入了一個childMeasureState臨時變量的計算,那么這個值的作用是什么呢?有何意義呢?說到這里不得不提API 11后引入的幾個標識位:

這些標識位上面的代碼中我們都有用到,而官方文檔對其作用的說明也是模棱兩可,源碼里的運用也不明朗,比如說我們看其它幾個與其相關的幾個方法:
~~~
public final int getMeasuredWidth() {
return mMeasuredWidth & MEASURED_SIZE_MASK;
}
public final int getMeasuredHeight() {
return mMeasuredHeight & MEASURED_SIZE_MASK;
}
public final int getMeasuredState() {
return (mMeasuredWidth&MEASURED_STATE_MASK)
| ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
& (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
}
~~~
這里大家注意getMeasuredWidth和getMeasuredHeight這兩個我們用來獲取控件測量寬高的方法,在其之中對其做了一個按位與的運算,然后才把這個測量值返回給我們,也就是說這個mMeasuredWidth和mMeasuredHeight里面應該還封裝了些什么對吧,那么我們來看其賦值,其賦值是在setMeasuredDimension方法下進行的:
~~~
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
// 省去無關代碼……
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
// 省去一行代碼……
}
~~~
也就是說當我們給控件設置最終測量尺寸時這個值就直接被賦予給了mMeasuredWidth和mMeasuredHeight這兩個成員變量……看到這里很多朋友蛋疼了,那有啥區別和意義呢?我們嘗試來翻翻系統自帶控件關于它的處理,其中TextView沒有涉及到這個參數的應用,而ImageView里則有:
~~~
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 省去海量代碼…………
widthSize = resolveSizeAndState(w, widthMeasureSpec, 0);
heightSize = resolveSizeAndState(h, heightMeasureSpec, 0);
// 省去一點代碼…………
}
~~~
在ImageView的onMeasure方法中使用resolveSizeAndState再次對計算得出的寬高進行解算,而這里的第三個參數直接傳的0,也就是不作任何處理~~~~~~~~蛋疼!真蛋疼,以前寡人也曾糾結過一段時間,后來在stackoverflow在找到兩個比較靠譜的答案:

大概意思就是當控件的測量尺寸比其父容器大時將會設置MEASURED_STATE_TOO_SMALL這個二進制值,而另一個stackoverflow的回答就更官方了:

注意右下角的用戶名和頭像,你就知道為什么這個回答有權威性了,鄙人是他腦殘粉。來我們好好翻一下Romain這段話的意思:“childMeasuredState這個值呢由View.getMeasuredState()這個方法返回,一個布局(或者按我的說法父容器)通過View.combineMeasuredStates()這個方法來統計其子元素的測量狀態。在大多數情況下你可以簡單地只傳遞0作為參數值,而子元素狀態值目前的作用只是用來告訴父容器在對其進行測量得出的測量值比它自身想要的尺寸要小,如果有必要的話一個對話框將會根據這個原因來重新校正它的尺寸。”So、可以看出,測量狀態對谷歌官方而言也還算個測試性的功能,具體鄙人也沒有找到很好的例證,如果大家誰找到了其具體的使用方法可以分享一下,這里我們還是就按照谷歌官方的建議依葫蘆畫瓢。好了這個問題就先到這里為止,我們繼續看,在測量子元素尺寸時我分了兩種情況:
~~~
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
// 累加子元素的實際寬度
parentDesireWidth += childActualWidth;
// 獲取子元素中高度最大值
parentDesireHeight = Math.max(parentDesireHeight, childActualHeight);
}
/*
* 如果為豎向排列
*/
else if (mOrientation == ORIENTATION_VERTICAL) {
// 累加子元素的實際高度
parentDesireHeight += childActualHeight;
// 獲取子元素中寬度最大值
parentDesireWidth = Math.max(parentDesireWidth, childActualWidth);
}
~~~
如果為橫/豎向排列,那么我們應該統計各個子元素的寬/高,而高/寬呢則不需要統計,我們取其最高/最寬的那個子元素的值即可,注意在上一節的處理中我們并沒有這樣去做哦!不知道大家發現沒~~~好了,onMeasure方法的邏輯就是這樣,如果你覺得好長,那么恭喜你,這只是我們的第一步,爾后還有幾個參數的處理~~~~~這時候你如果運行會發現什么都沒有,因為onMeasure方法的作用僅僅是測量的一步,按照官方的說法,Android對Viewgroup的測量由兩方面構成:一是對父容器和子元素大小尺寸的測量主要體現在onMeasure方法,二是對父容器的子元素在其區域內的定位主要體現在onLayout方法。也就是會說,即便我們完成了測量但沒告訴兒子們該出現在哪的話也不會有任何顯示效果,OK,現在我們來看看onLayout方法的邏輯處理:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量標識值
private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默認值
private int mMaxRow = DEFAULT_MAX_ROW;// 最大行數
private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列數
private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默認橫向
// 省去構造方法…………
// 省去上面已經給過的onMeasure方法…………
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
/*
* 如果父容器下有子元素
*/
if (getChildCount() > 0) {
// 聲明臨時變量存儲寬高倍增值
int multi = 0;
/*
* 遍歷子元素
*/
for (int i = 0; i < getChildCount(); i++) {
// 獲取對應遍歷下標的子元素
View child = getChildAt(i);
/*
* 如果該子元素沒有以“不占用空間”的方式隱藏則表示其需要被測量計算
*/
if (child.getVisibility() != View.GONE) {
// 獲取子元素布局參數
MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
// 獲取控件尺寸
int childActualSize = child.getMeasuredWidth();// child.getMeasuredHeight()
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
// 確定子元素左上、右下坐標
child.layout(getPaddingLeft() + mlp.leftMargin + multi, getPaddingTop() + mlp.topMargin, childActualSize + getPaddingLeft()
+ mlp.leftMargin + multi, childActualSize + getPaddingTop() + mlp.topMargin);
// 累加倍增值
multi += childActualSize + mlp.leftMargin + mlp.rightMargin;
}
/*
* 如果為豎向排列
*/
else if (mOrientation == ORIENTATION_VERTICAL) {
// 確定子元素左上、右下坐標
child.layout(getPaddingLeft() + mlp.leftMargin, getPaddingTop() + mlp.topMargin + multi, childActualSize + getPaddingLeft()
+ mlp.leftMargin, childActualSize + getPaddingTop() + mlp.topMargin + multi);
// 累加倍增值
multi += childActualSize + mlp.topMargin + mlp.bottomMargin;
}
}
}
}
}
// 省去四個屌毛方法……
}
~~~
比起對onMeasure方法的邏輯處理,onLayout方法相對簡單,主要是在對子元素layout的地方需要我們一點計算思維,也不是很復雜,哥相信你能懂,畢竟注釋如此清楚,來我們嘗試用一下我們的布局:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#ffffff" >
<com.aigestudio.customviewdemo.views.SquareLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="12dp"
android:layout_margin="5dp"
android:paddingRight="7dp"
android:paddingBottom="20dp"
android:layout_gravity="center"
android:background="#679135" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#125793"
android:text="tomorrow"
android:textSize="24sp"
android:textStyle="bold"
android:typeface="serif" />
<Button
android:layout_width="50dp"
android:layout_height="100dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginTop="30dp"
android:background="#495287"
android:text="AigeStudio" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp"
android:background="#976234"
android:scaleType="centerCrop"
android:src="@drawable/lovestory_little" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#594342"
android:text="AigeStudio" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#961315"
android:text="AigeStudio" />
</com.aigestudio.customviewdemo.views.SquareLayout>
</LinearLayout>
~~~

下面是運行后顯示的效果:

將排列方式改為縱向排列:
`private int mOrientation = ORIENTATION_VERTICAL;// 排列方向默認橫向 `
再來瞅瞅ADT的顯示效果:

在運行看看:

看樣子目測還是很完美,不過這只是我們偉大的第一步而已!如我多次強調,控件的測量一定要盡可能地考慮到所有因素,這樣你的控件才能立于N次不倒的暴力測試中,現在開始我們的第二步,max_row和max_column屬性的計算:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量標識值
private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默認值
private int mMaxRow = DEFAULT_MAX_ROW;// 最大行數
private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列數
private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默認橫向
public SquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// 初始化最大行列數
mMaxRow = mMaxColumn = 2;
}
// 省去onMeasure方法…………
// 省去onLayout方法…………
// 省去四個屌毛方法……
}
~~~
首先呢在構造方法內初始化我們的最大行列數,不然我們可不可能造出Integer.MAX_VALUE這么多的子元素~~~~~
~~~
// 初始化最大行列數
mMaxRow = mMaxColumn = 2;
~~~
我們的SquareLayout中有5個子元素,那么這里就暫定我們的最大行列均為2好了,首先來看看onMeasure方法的邏輯處理,變動較大我先貼代碼好了:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量標識值
private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默認值
private int mMaxRow = DEFAULT_MAX_ROW;// 最大行數
private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列數
private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默認橫向
// 省去構造方法…………
@SuppressLint("NewApi")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/*
* 聲明臨時變量存儲父容器的期望值
* 該值應該等于父容器的內邊距加上所有子元素的測量寬高和外邊距
*/
int parentDesireWidth = 0;
int parentDesireHeight = 0;
// 聲明臨時變量存儲子元素的測量狀態
int childMeasureState = 0;
/*
* 如果父容器內有子元素
*/
if (getChildCount() > 0) {
// 聲明兩個一維數組存儲子元素寬高數據
int[] childWidths = new int[getChildCount()];
int[] childHeights = new int[getChildCount()];
/*
* 那么就遍歷子元素
*/
for (int i = 0; i < getChildCount(); i++) {
// 獲取對應遍歷下標的子元素
View child = getChildAt(i);
/*
* 如果該子元素沒有以“不占用空間”的方式隱藏則表示其需要被測量計算
*/
if (child.getVisibility() != View.GONE) {
// 測量子元素并考量其外邊距
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
// 比較子元素測量寬高并比較取其較大值
int childMeasureSize = Math.max(child.getMeasuredWidth(), child.getMeasuredHeight());
// 重新封裝子元素測量規格
int childMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasureSize, MeasureSpec.EXACTLY);
// 重新測量子元素
child.measure(childMeasureSpec, childMeasureSpec);
// 獲取子元素布局參數
MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
/*
* 考量外邊距計算子元素實際寬高并將數據存入數組
*/
childWidths[i] = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;
childHeights[i] = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;
// 合并子元素的測量狀態
childMeasureState = combineMeasuredStates(childMeasureState, child.getMeasuredState());
}
}
// 聲明臨時變量存儲行/列寬高
int indexMultiWidth = 0, indexMultiHeight = 0;
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
/*
* 如果子元素數量大于限定值則進行折行計算
*/
if (getChildCount() > mMaxColumn) {
// 計算產生的行數
int row = getChildCount() / mMaxColumn;
// 計算余數
int remainder = getChildCount() % mMaxColumn;
// 聲明臨時變量存儲子元素寬高數組下標值
int index = 0;
/*
* 遍歷數組計算父容器期望寬高值
*/
for (int x = 0; x < row; x++) {
for (int y = 0; y < mMaxColumn; y++) {
// 單行寬度累加
indexMultiWidth += childWidths[index];
// 單行高度取最大值
indexMultiHeight = Math.max(indexMultiHeight, childHeights[index++]);
}
// 每一行遍歷完后將該行寬度與上一行寬度比較取最大值
parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);
// 每一行遍歷完后累加各行高度
parentDesireHeight += indexMultiHeight;
// 重置參數
indexMultiWidth = indexMultiHeight = 0;
}
/*
* 如果有余數表示有子元素未能占據一行
*/
if (remainder != 0) {
/*
* 遍歷剩下的這些子元素將其寬高計算到父容器期望值
*/
for (int i = getChildCount() - remainder; i < getChildCount(); i++) {
indexMultiWidth += childWidths[i];
indexMultiHeight = Math.max(indexMultiHeight, childHeights[i]);
}
parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);
parentDesireHeight += indexMultiHeight;
indexMultiWidth = indexMultiHeight = 0;
}
}
/*
* 如果子元素數量還沒有限制值大那么直接計算即可不須折行
*/
else {
for (int i = 0; i < getChildCount(); i++) {
// 累加子元素的實際高度
parentDesireHeight += childHeights[i];
// 獲取子元素中寬度最大值
parentDesireWidth = Math.max(parentDesireWidth, childWidths[i]);
}
}
}
/*
* 如果為豎向排列
*/
else if (mOrientation == ORIENTATION_VERTICAL) {
if (getChildCount() > mMaxRow) {
int column = getChildCount() / mMaxRow;
int remainder = getChildCount() % mMaxRow;
int index = 0;
for (int x = 0; x < column; x++) {
for (int y = 0; y < mMaxRow; y++) {
indexMultiHeight += childHeights[index];
indexMultiWidth = Math.max(indexMultiWidth, childWidths[index++]);
}
parentDesireHeight = Math.max(parentDesireHeight, indexMultiHeight);
parentDesireWidth += indexMultiWidth;
indexMultiWidth = indexMultiHeight = 0;
}
if (remainder != 0) {
for (int i = getChildCount() - remainder; i < getChildCount(); i++) {
indexMultiHeight += childHeights[i];
indexMultiWidth = Math.max(indexMultiHeight, childWidths[i]);
}
parentDesireHeight = Math.max(parentDesireHeight, indexMultiHeight);
parentDesireWidth += indexMultiWidth;
indexMultiWidth = indexMultiHeight = 0;
}
} else {
for (int i = 0; i < getChildCount(); i++) {
// 累加子元素的實際寬度
parentDesireWidth += childWidths[i];
// 獲取子元素中高度最大值
parentDesireHeight = Math.max(parentDesireHeight, childHeights[i]);
}
}
}
/*
* 考量父容器內邊距將其累加到期望值
*/
parentDesireWidth += getPaddingLeft() + getPaddingRight();
parentDesireHeight += getPaddingTop() + getPaddingBottom();
/*
* 嘗試比較父容器期望值與Android建議的最小值大小并取較大值
*/
parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());
parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());
}
// 確定父容器的測量寬高
setMeasuredDimension(resolveSizeAndState(parentDesireWidth, widthMeasureSpec, childMeasureState),
resolveSizeAndState(parentDesireHeight, heightMeasureSpec, childMeasureState << MEASURED_HEIGHT_STATE_SHIFT));
}
// 省去onLayout方法…………
// 省去四個屌毛方法……
}
~~~
邏輯計算變動較大,首先在遍歷子元素時我沒有直接對橫縱向排列進行計算而是先用兩個數組將子元素的寬高存儲起來:
~~~
@SuppressLint("NewApi")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 省去幾行代碼…………
/*
* 如果父容器內有子元素
*/
if (getChildCount() > 0) {
// 聲明兩個一維數組存儲子元素寬高數據
int[] childWidths = new int[getChildCount()];
int[] childHeights = new int[getChildCount()];
/*
* 那么就遍歷子元素
*/
for (int i = 0; i < getChildCount(); i++) {
// 省省省……
/*
* 如果該子元素沒有以“不占用空間”的方式隱藏則表示其需要被測量計算
*/
if (child.getVisibility() != View.GONE) {
// 省去N行代碼……
/*
* 考量外邊距計算子元素實際寬高并將數據存入數組
*/
childWidths[i] = child.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;
childHeights[i] = child.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;
// 省去一行代碼……
}
}
// 聲明臨時變量存儲行/列寬高
int indexMultiWidth = 0, indexMultiHeight = 0;
// 省去無數行代碼……………………
}
// 省去一行代碼……
}
然后上面還聲明兩個臨時變量indexMultiWidth和indexMultiHeight用來分別存儲單行/列的寬高并將該行計算后的結果累加到父容器的期望值,這里我們就看看橫向排列的邏輯:
[java] view plain copy print?
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
/*
* 如果子元素數量大于限定值則進行折行計算
*/
if (getChildCount() > mMaxColumn) {
// 計算產生的行數
int row = getChildCount() / mMaxColumn;
// 計算余數
int remainder = getChildCount() % mMaxColumn;
// 聲明臨時變量存儲子元素寬高數組下標值
int index = 0;
/*
* 遍歷數組計算父容器期望寬高值
*/
for (int x = 0; x < row; x++) {
for (int y = 0; y < mMaxColumn; y++) {
// 單行寬度累加
indexMultiWidth += childWidths[index];
// 單行高度取最大值
indexMultiHeight = Math.max(indexMultiHeight, childHeights[index++]);
}
// 每一行遍歷完后將該行寬度與上一行寬度比較取最大值
parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);
// 每一行遍歷完后累加各行高度
parentDesireHeight += indexMultiHeight;
// 重置參數
indexMultiWidth = indexMultiHeight = 0;
}
/*
* 如果有余數表示有子元素未能占據一行
*/
if (remainder != 0) {
/*
* 遍歷剩下的這些子元素將其寬高計算到父容器期望值
*/
for (int i = getChildCount() - remainder; i < getChildCount(); i++) {
indexMultiWidth += childWidths[i];
indexMultiHeight = Math.max(indexMultiHeight, childHeights[i]);
}
parentDesireWidth = Math.max(parentDesireWidth, indexMultiWidth);
parentDesireHeight += indexMultiHeight;
indexMultiWidth = indexMultiHeight = 0;
}
}
/*
* 如果子元素數量還沒有限制值大那么直接計算即可不須折行
*/
else {
for (int i = 0; i < getChildCount(); i++) {
// 累加子元素的實際高度
parentDesireHeight += childHeights[i];
// 獲取子元素中寬度最大值
parentDesireWidth = Math.max(parentDesireWidth, childWidths[i]);
}
}
}
~~~
計算我分了兩種情況,子元素數量如果小于我們的限定值,例如我們布局下只有2個子元素,而我們的限定值為3,這時候就沒必要計算折行,而另一種情況則是子元素數量大于我們的限定值,例如我們的布局下有7個子元素而我們的限定值為3,這時當我們橫向排列到第三個子元素后就得折行了,在新的一行開始排列,在這種情況下,我們先計算了能被整除的子元素數:例如7/3為2余1,也就意味著我們此時能排滿的只有兩行,而多出來的那一行只有一個子元素,分別計算兩種情況累加結果就OK了。縱向排列類似不說了,這里我邏輯比較臃腫,但是可以讓大家很好理解,如果你Math好可以簡化很多邏輯,不說了,既然onMeasure方法改動了,那么我們的onLayout方法也得跟上時代的步伐才行:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
private static final int ORIENTATION_HORIZONTAL = 0, ORIENTATION_VERTICAL = 1;// 排列方向的常量標識值
private static final int DEFAULT_MAX_ROW = Integer.MAX_VALUE, DEFAULT_MAX_COLUMN = Integer.MAX_VALUE;// 最大行列默認值
private int mMaxRow = DEFAULT_MAX_ROW;// 最大行數
private int mMaxColumn = DEFAULT_MAX_COLUMN;// 最大列數
private int mOrientation = ORIENTATION_HORIZONTAL;// 排列方向默認橫向
// 省去構造方法…………
// 省去上面已經給過的onMeasure方法…………
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
/*
* 如果父容器下有子元素
*/
if (getChildCount() > 0) {
// 聲明臨時變量存儲寬高倍增值
int multi = 0;
// 指數倍增值
int indexMulti = 1;
// 聲明臨時變量存儲行/列寬高
int indexMultiWidth = 0, indexMultiHeight = 0;
// 聲明臨時變量存儲行/列臨時寬高
int tempHeight = 0, tempWidth = 0;
/*
* 遍歷子元素
*/
for (int i = 0; i < getChildCount(); i++) {
// 獲取對應遍歷下標的子元素
View child = getChildAt(i);
/*
* 如果該子元素沒有以“不占用空間”的方式隱藏則表示其需要被測量計算
*/
if (child.getVisibility() != View.GONE) {
// 獲取子元素布局參數
MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
// 獲取控件尺寸
int childActualSize = child.getMeasuredWidth();// child.getMeasuredHeight()
/*
* 如果為橫向排列
*/
if (mOrientation == ORIENTATION_HORIZONTAL) {
/*
* 如果子元素數量比限定值大
*/
if (getChildCount() > mMaxColumn) {
/*
* 根據當前子元素進行布局
*/
if (i < mMaxColumn * indexMulti) {
child.layout(getPaddingLeft() + mlp.leftMargin + indexMultiWidth, getPaddingTop() + mlp.topMargin + indexMultiHeight,
childActualSize + getPaddingLeft() + mlp.leftMargin + indexMultiWidth, childActualSize + getPaddingTop()
+ mlp.topMargin + indexMultiHeight);
indexMultiWidth += childActualSize + mlp.leftMargin + mlp.rightMargin;
tempHeight = Math.max(tempHeight, childActualSize) + mlp.topMargin + mlp.bottomMargin;
/*
* 如果下一次遍歷到的子元素下標值大于限定值
*/
if (i + 1 >= mMaxColumn * indexMulti) {
// 那么累加高度到高度倍增值
indexMultiHeight += tempHeight;
// 重置寬度倍增值
indexMultiWidth = 0;
// 增加指數倍增值
indexMulti++;
}
}
} else {
// 確定子元素左上、右下坐標
child.layout(getPaddingLeft() + mlp.leftMargin + multi, getPaddingTop() + mlp.topMargin, childActualSize
+ getPaddingLeft() + mlp.leftMargin + multi, childActualSize + getPaddingTop() + mlp.topMargin);
// 累加倍增值
multi += childActualSize + mlp.leftMargin + mlp.rightMargin;
}
}
/*
* 如果為豎向排列
*/
else if (mOrientation == ORIENTATION_VERTICAL) {
if (getChildCount() > mMaxRow) {
if (i < mMaxRow * indexMulti) {
child.layout(getPaddingLeft() + mlp.leftMargin + indexMultiWidth, getPaddingTop() + mlp.topMargin + indexMultiHeight,
childActualSize + getPaddingLeft() + mlp.leftMargin + indexMultiWidth, childActualSize + getPaddingTop()
+ mlp.topMargin + indexMultiHeight);
indexMultiHeight += childActualSize + mlp.topMargin + mlp.bottomMargin;
tempWidth = Math.max(tempWidth, childActualSize) + mlp.leftMargin + mlp.rightMargin;
if (i + 1 >= mMaxRow * indexMulti) {
indexMultiWidth += tempWidth;
indexMultiHeight = 0;
indexMulti++;
}
}
} else {
// 確定子元素左上、右下坐標
child.layout(getPaddingLeft() + mlp.leftMargin, getPaddingTop() + mlp.topMargin + multi, childActualSize
+ getPaddingLeft() + mlp.leftMargin, childActualSize + getPaddingTop() + mlp.topMargin + multi);
// 累加倍增值
multi += childActualSize + mlp.topMargin + mlp.bottomMargin;
}
}
}
}
}
}
// 省去四個屌毛方法……
}
~~~
onLayout方法就不具體說了,其實現要比onMeasure方法簡單,我們稍微更改下布局文件盡可能地測試多種情況:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#ffffff" >
<com.aigestudio.customviewdemo.views.SquareLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#679135"
android:paddingBottom="20dp"
android:paddingLeft="5dp"
android:paddingRight="7dp"
android:paddingTop="12dp" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#125793"
android:text="tomorrow"
android:textSize="24sp"
android:textStyle="bold"
android:typeface="serif" />
<Button
android:layout_width="50dp"
android:layout_height="100dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginTop="30dp"
android:background="#495287"
android:text="AigeStudio" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp"
android:background="#976234" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/lovestory_little" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#594342"
android:text="AigeStudio" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#961315"
android:text="Welcome AigeStudio" />
</com.aigestudio.customviewdemo.views.SquareLayout>
</LinearLayout>
~~~
下面看看ADT中的直接顯示效果:

運行后的顯示效果:

換成縱向排列看看:

運行后的效果:

嘗試更改下縱向排列時的限制值:
~~~
// 初始化最大行列數
mMaxRow = 2;
mMaxColumn =3;
~~~
直接看運行效果:

表示暫時木有發現什么大問題,OK,這兩個屬性值的實現就到這里,雖然只有兩個屬性值 = = TMD實在是菊緊啊,可想而知LinearLayout等布局這么多屬性控制是有多蛋疼了么,不過如我文章開頭所說,我們的這個自定義布局實用意義不大,主要還是給大家演示了解下自定義布局是有多么蛋疼、啊不……是由多么復雜,像系統自帶的那些布局控件都是經過N多update版本才有今天,即便如此,依然還有很多BUG,不過大多不會影響實際使用我們也可以很好地解決,所以,再次強調、控件的測量是一個極為嚴謹縝密的過程,稍有不慎你的控件便到處都會是說不出的BUG~~~~~上一節我們為了能讓我們的自定義布局能對外邊距進行計算,我們定義了一個內部類LayoutParams繼承于MarginLayoutParams但是其中什么也沒做,而這一節呢我們沒有定義這么一個內部類而是直接返回MarginLayoutParams的實例,我們之所以能從布局參數中獲取到外邊距的屬性值,比如:
?
~~~
// 獲取子元素布局參數
MarginLayoutParams mlp = (MarginLayoutParams) child.getLayoutParams();
~~~
然后各種
~~~
mlp.leftMargin
mlp.topMargin
mlp.rightMargin
mlp.bottomMargin
~~~
是因為在MarginLayoutParams中已經為我們定義好了這些參數,具體代碼就不貼了,如果我們定義了自己的布局,我們也可以去定義自己的布局參數,比如我們在其中定義子元素在布局中的對其方式:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去無數代碼…………
public static class LayoutParams extends MarginLayoutParams {
public int mGravity;// 對齊方式
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
}
}
~~~
然后呢我們就要修改那四個屌毛方法返回我們自己定義的LayoutParams:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去無數代碼…………
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
// 省去LayoutParams的定義…………
}
~~~
然后你就可以通過其獲取這個對其方式的值:
~~~
// 獲取子元素布局參數
LayoutParams mlp = (LayoutParams) child.getLayoutParams();
if (mlp.mGravity == xxxxxxx) {
………………………………………………………………
}
~~~
用法跟margin類似,那么我們如何為該變量賦值呢?方法多種多樣,可以寫死可以直接調用賦值,這里我們來看另外的一種方式:通過xml在布局文件中直接設置其屬性值,我們在使用xml進行布局時經常會使用這樣的方式指定屬性值:
~~~
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#125793"
android:text="tomorrow"
android:textSize="24sp"
android:textStyle="bold"
android:typeface="serif"
~~~
使用起來灰常方便,而這里我們也可以自定義屬于自己的xml屬性,方法非常非常簡單,首先需要我們在declare-styleable標簽下定義我們的各類屬性:
~~~
<!-- http://blog.csdn.net/aigestudio -->
<declare-styleable name="SquareLayout">
<attr name="my_gravity" format="enum">
<enum name="left" value="0" />
<enum name="right" value="1" />
<enum name="center" value="2" />
<enum name="top" value="3" />
<enum name="bottom" value="4" />
</attr>
</declare-styleable>
~~~
一般情況下,declare-styleable的定義存放在values/attr.xml文件中,屬性定義好了我們就該在布局中使用這些屬性,使用方法也很簡單,比如我們在SquareLayout的Button中應用my_gravity屬性:
~~~
<Button
xmlns:aigestudio="http://schemas.android.com/apk/res/com.aigestudio.customviewdemo"
aigestudio:my_gravity="left" />
~~~
在使用自定義屬性前聲明我們包內的命名空間即可,你可以直接寫在布局文件的根布局下,命名空間的聲明有兩種寫法,上面是其一,其格式如下:
`xmlns:你想要的名字="http://schemas.android.com/apk/res/完整包名" `
第二種方式如果你是用的是Studio,IDE則會提示你使用該方式:
`xmlns:你想要的名字="http://schemas.android.com/apk/res-auto" `
都可以,最后就是從xml中獲取這些屬性了,我們可以直接簡單地通過帶有AttributeSet對象的構造方法來獲取:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去無數代碼…………
public static class LayoutParams extends MarginLayoutParams {
public int mGravity;// 對齊方式
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
/*
* 獲取xml對應屬性
*/
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.SquareLayout);
mGravity = a.getInt(R.styleable.SquareLayout_my_gravity, 0);
}
public LayoutParams(int width, int height) {
super(width, height);
}
}
}
~~~
通過Context的obtainStyledAttributes方法注入AttributeSet對象和我們資源文件中定義的declare-styleable屬性獲取一個TypedArray對象,我們通過這個TypedArray對象各種相應的方法來獲取參數值,本來呢我之前寫了很長的篇幅來給大家介紹這其中的過程,后來發現實在太繁瑣太多干脆刪了重寫旨在教會大家如何用即可。Android支持如下十種不同類型的屬性定義:
~~~
<!-- http://blog.csdn.net/aigestudio -->
<declare-styleable name="AttrView">
<!-- 引用資源 -->
<attr name="image" format="reference" />
<!-- 顏色 -->
<attr name="text_color" format="color" />
<!-- 布爾值 -->
<attr name="text_display" format="boolean" />
<!-- 尺寸大小 -->
<attr name="temp1" format="dimension" />
<!-- 浮點值 -->
<attr name="temp2" format="float" />
<!-- 整型值 -->
<attr name="temp3" format="integer" />
<!-- 字符串 -->
<attr name="text" format="string" />
<!-- 百分比 -->
<attr name="alpha" format="fraction" />
<!-- 枚舉 -->
<attr name="text_align" format="integer">
<enum name="left" value="0" />
<enum name="right" value="1" />
<enum name="center" value="2" />
</attr>
<!-- 位運算 -->
<attr name="text_optimize" format="integer">
<flag name="anti" value="0x001" />
<flag name="dither" value="0x002" />
<flag name="linear" value="0x004" />
</attr>
</declare-styleable>
~~~
name都是我亂取的不要在意,主要看后面的format,這些類型都很好理解,它們在TypedArray中都有各種對應或重載的方法,比如獲取color的getColor方法,上面我們獲取int的getInt等等,這里對大家來說比較新穎的是fraction百分比這個類型,其在TypedArray的對應方法如下:
`getFraction(int index, int base, int pbase, float defValue) `
第一個參數很好理解表示我們定義的屬性資源ID,最后一個參數呢也和前面的getInt類似,主要是這第二、三個參數,其作用是分開來的,當我們在xml中使用百分比屬性時有兩種寫法,一種是標準的10%而另一種是帶p的10%p:
~~~
aigestudio:alpha="10%"
aigestudio:alpha="10%p"
~~~
當屬性值為10%的時候base參數起作用,我們此時獲取的參數值就等于(10% * base),而pbase參數則無效,同理當屬性值為10%p時參數值就等于(10% * pbase)而base無效,Just it。還有兩個比較類似的類型:枚舉和位運算,這兩個類型也很好理解,枚舉嘛就是從眾多的選項中選一個,而位運算則可以選多個并通過“|”組合各種結果:
`aigestudio:text_optimize="anti|dither" `
這種寫法相信大家也很常見,比如layout_gravity屬性就可以以類似的方式多選,這種方式有一個好處就是我們不用在屬性聲明中定義太多的值,上面的text_optimize屬性只有三個對應值,但是在code中我們可以以位運算的方式組合這三個參數值:
~~~
/*
* 畫筆優化的標識位們
*/
private static final int OPTIMIZE_ANTI = 0x001, OPTIMIZE_DITHER = 0x002, OPTIMIZE_LINEAR = 0x004, OPTIMIZE_ANTI_DITHER = 0x003, OPTIMIZE_ANTI_LINEAR = 0x005, OPTIMIZE_DITHER_LINEAR = 0x006, OPTIMIZE_ALL = 0x007;
~~~
通過三個參數值的位運算我們實質上就得到了7種不同的結果,Just it。xml屬性值的定義不難不多用幾次就會就不多說了,上面呢我們通過自定義的屬性mGravity來嘗試定義子元素相對于父容器的對其方式,而事實上Android提供給我們一個簡便的方法去計算這玩意,Android定義了Gravity類來實現我們對對其方式的計算,其中定義了大量的常量值定義不同對其方式,比如什么左對齊、右對齊、水平居中亂七八糟的等等,也提供了多個方法來實現計算,使用方式呢也不難,比如上面的布局參數我們換成如下方式:
~~~
/**
*
* @author AigeStudio {@link http://blog.csdn.net/aigestudio}
* @since 2015/1/23
*
*/
public class SquareLayout extends ViewGroup {
// 省去無數代碼…………
public static class LayoutParams extends MarginLayoutParams {
public int mGravity = Gravity.LEFT | Gravity.RIGHT;// 對齊方式
// 省去沒變的代碼…………
}
}
~~~
而在我們的xml屬性定義中則可以直接使用android:layout_gravity這樣的name而無需定義類型值:
~~~
<declare-styleable name="SquareLayout">
<attr name="android:layout_gravity" />
</declare-styleable>
~~~
這樣則表示我們的屬性使用的Android自帶的標簽,之后我們只需根據布局文件中layout_gravity屬性的值調用Gravity類下的方法去計算對齊方式則可,Gravity類下的方法很好用,為什么這么說呢?因為其可以說是無關布局的,拿最簡單的一個來說:
[java] view plain copy print?
public static void apply(int gravity, int w, int h, Rect container, Rect outRect)
第一個參數表示我們的對其方式值,第二三個參數呢則表示我們要對齊的元素,這里通俗地說就是我們父容器下的子元素,而container參數表示的則是我們父容器的矩形區域,最后一個參數是接收計算后子元素位置區域的矩形對象,隨便new個傳進去就行,可見apply方式是根據矩形區域來計算對其方式的,所以說非常好用,我們只需在onLayout方法中確定出父容器的矩形區域就可以輕松地計算出子元素根據對其方式出現在父容器中的矩形區域,這一個過程留給大家自行嘗試,我就不多說了,TMD說的太多,又忘了上一節的那個問題了、肏!!!!好吧,下一節再說那個問題,哦!對了,還有一個擦邊球的東西忘了講,在Android很多的布局控件中都會重寫這么一個方法:
~~~
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
~~~
并且都會一致地返回false,其作用是告訴framework我們當前的布局不是一個滾動的布局,我們這里的自定義布局控件也重寫了該方法~~~好好了了,不講了,這節就到此為止,接下來就是下一節,接踵而至in two days~~~~~~thx
源碼下載:[傳送門](http://download.csdn.net/detail/aigestudio/8415399)