問題:如何建立一個如所示的布局?
圖1
(原文地址:http://blog.csdn.net/vector_yi/article/details/24415537)
你可能會說,利用RelativeLayout和margins就可以實現。的確,如下XML代碼可以簡單地構建一個類似的布局:
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" > <View android:layout_width ="100dp" android:layout_height ="150dp" android:background ="#FF0000" /> <View android:layout_width ="100dp" android:layout_height ="150dp" android:layout_marginLeft ="30dp" android:layout_marginTop ="20dp" android:background ="#00FF00" /> <View android:layout_width ="100dp" android:layout_height ="150dp" android:layout_marginLeft ="60dp" android:layout_marginTop ="40dp" android:background ="#0000FF" /></RelativeLayout>
效果2:
圖2
但是當遇到複雜、要求可變的類似布局時,利用margins可能就會顯得操作很繁雜。在此,我們來看另一種建立類似布局的方式---自訂ViewGroup好處有以下幾點:
- 當你將這個布局應用到不同Activity中時更加容易維護
- 可以利用自訂屬性來自訂ViewGroup中的每個子View
- 更加簡潔可讀的XML檔案內容
- 如果需要改變margin的時候,不需要手動的去計算每個子View的margin
一、理解Android繪製一個View的步驟 關於繪製View的步驟,可以參見Android官方文檔:http://developer.android.com/guide/topics/ui/how-android-draws.html 在此,我們重點來關注ViewGroup的繪製過程: 1.處理ViewGroup的width和height. 處理width及height的操作在onMeasure()方法中進行,在此方法內,ViewGroup會根據它的子View來計算自身所佔用的布局空間。 2.布局到頁面上 這點操作在onLayout()方法中進行,在此方法中,ViewGroup會根據從onMeasure()中得到的資訊將其每一個子View繪製出來。
二、構建CascadeLayout類 首先在XML布局檔案中添加CascadeLayout:
<FrameLayout <!--自訂命名空間,以便在下文中使用自訂的屬性--> xmlns:cascade ="http://schemas.android.com/apk/res/com.manning.androidhacks.hack003" xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" > <com.manning.androidhacks.hack003.view.CascadeLayout android:layout_width ="fill_parent" android:layout_height ="fill_parent" cascade:horizontal_spacing ="30dp"<!--因為前面添加了cascade命名空間,所以此處可以使用自訂屬性--> cascade:vertical_spacing ="20dp" > <View android:layout_width ="100dp" android:layout_height ="150dp" cascade:layout_vertical_spacing ="90dp"<!--為子View添加的自訂屬性,將在本文第三部分用到--> android:background ="#FF0000" /> <View android:layout_width ="100dp" android:layout_height ="150dp" android:background ="#00FF00" /> <View android:layout_width ="100dp" android:layout_height ="150dp" android:background ="#0000FF" /> </com.manning.androidhacks.hack003.view.CascadeLayout></FrameLayout>
要使用這些自訂的屬性,我們必須要定義它。 在res/values檔案夾下建立一個attrs.xml檔案:
<? xml version ="1.0" encoding= "utf-8" ?><resources> <declare-styleable name= "CascadeLayout" > <attr name= "horizontal_spacing" format = "dimension" /> <attr name= "vertical_spacing" format = "dimension" /> </declare-styleable></resources>
然後,當我們在建立CascadeLayout且沒有為其指定horizontal_spacing與vertical_spacing時,需要有一個預設值。我們將這個預設值預先定義好並存放在res/values檔案夾下的dimens.xml中:
<? xml version ="1.0" encoding= "utf-8" ?><resources> <dimen name= "cascade_horizontal_spacing" >10dp</dimen> <dimen name= "cascade_vertical_spacing" >10dp</dimen></resources>
最後,我們需要建立一個名為CascadeLayout的Java類,它繼承了ViewGroup並重寫了onMeasure()與OnLayout()方法。1.CascadeLayout的建構函式
public CascadeLayout (Context context, AttributeSet attrs) { super( context, attrs); TypedArray a = context .obtainStyledAttributes (attrs , R. styleable. CascadeLayout ); try { mHorizontalSpacing = a. getDimensionPixelSize( R. styleable. CascadeLayout_horizontal_spacing , getResources ().getDimensionPixelSize ( R. dimen. cascade_horizontal_spacing )); mVerticalSpacing = a. getDimensionPixelSize( R. styleable. CascadeLayout_vertical_spacing , getResources () .getDimensionPixelSize (R .dimen .cascade_vertical_spacing )); } finally { a .recycle (); }2.構建自訂的LayoutParams類 LayoutParams類將作為CascadeLayout的內部類存在,它將儲存每個子View的x,y座標。定義如下:
public static class LayoutParams extends ViewGroup .LayoutParams { int x; int y; public LayoutParams( Context context , AttributeSet attrs) { super (context , attrs ); } public LayoutParams( int w , int h ) { super (w , h ); } }
3.重寫onMeasure()方法 onMeasure()方法將是CascadeLayout類中最關鍵的部分,這個方法不僅計算整個ViewGroup所佔用的布局空間,還將計算出每個子View所佔用的布局空間。
@Override protected void onMeasure (int widthMeasureSpec , int heightMeasureSpec ) { int width = 0; int height = getPaddingTop (); final int count = getChildCount (); for ( int i = 0; i < count; i++) { View child = getChildAt (i ); measureChild (child , widthMeasureSpec , heightMeasureSpec ); LayoutParams lp = (LayoutParams ) child .getLayoutParams (); width = getPaddingLeft () + mHorizontalSpacing * i; lp .x = width; lp .y = height; width += child .getMeasuredWidth (); height += mVerticalSpacing ; } width += getPaddingRight (); height += getChildAt (getChildCount () - 1). getMeasuredHeight () + getPaddingBottom (); setMeasuredDimension ( resolveSize( width, widthMeasureSpec ), resolveSize( height, heightMeasureSpec )); }
4.最後一步,重寫onLayout()方法 代碼很簡單,就是讓每個子View都調用layout()方法。
@Override protected void onLayout (boolean changed, int l , int t , int r , int b ) { final int count = getChildCount (); for ( int i = 0; i < count; i++) { View child = getChildAt (i ); LayoutParams lp = ( LayoutParams ) child .getLayoutParams (); child .layout (lp .x , lp .y , lp .x + child. getMeasuredWidth (), lp .y + child .getMeasuredHeight ()); } }
至此,就利用自訂的ViewGroup建立了一個和圖2一樣效果的布局頁面。
三、為子View添加自訂屬性
既然費了這麼大勁,怎麼可能就和之前幾行XML代碼效果一樣?下面,我們就來為CascadeLayout中的子View添加自訂屬性: 首先,在之前建立的attrs.xml中添加如下代碼:
<declare-styleable name="CascadeLayout_LayoutParams"> <attr name="layout_vertical_spacing" format="dimension" /></declare-styleable>
因為這個新添加的屬性是以 layout_ 開頭的,所以它會被添加到LayoutParams中去。我們可以在之前自訂的內部類LayoutParams中的建構函式中讀取到這個屬性,將第一個建構函式改為:
public LayoutParams (Context context, AttributeSet attrs) { super (context , attrs ); TypedArray a = context .obtainStyledAttributes (attrs , R. styleable. CascadeLayout_LayoutParams ); try { verticalSpacing = a .getDimensionPixelSize ( R .styleable .CascadeLayout_LayoutParams_layout_vertical_spacing , -1 ); } finally { a .recycle (); } }
既然添加了新的自訂屬性,就必須在onMeasure()方法中對其加以處理:
@Override protected void onMeasure (int widthMeasureSpec , int heightMeasureSpec ) { int width = getPaddingLeft (); int height = getPaddingTop (); int verticalSpacing ; final int count = getChildCount (); for ( int i = 0; i < count; i++) { verticalSpacing = mVerticalSpacing ; View child = getChildAt (i ); measureChild (child , widthMeasureSpec , heightMeasureSpec ); LayoutParams lp = ( LayoutParams ) child .getLayoutParams (); width = getPaddingLeft () + mHorizontalSpacing * i; lp .x = width; lp .y = height; if (lp .verticalSpacing >= 0 ) { verticalSpacing = lp .verticalSpacing ; } width += child .getMeasuredWidth (); height += verticalSpacing ; } width += getPaddingRight (); height += getChildAt (getChildCount () - 1). getMeasuredHeight () + getPaddingBottom (); setMeasuredDimension ( resolveSize( width, widthMeasureSpec ), resolveSize( height, heightMeasureSpec )); }
最後附上完整的CascadeLayout代碼:
package com.manning.androidhacks.hack003.view;import android.content.Context;import android.content.res.TypedArray;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;import com.manning.androidhacks.hack003.R;public class CascadeLayout extends ViewGroup { private int mHorizontalSpacing; private int mVerticalSpacing; public CascadeLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CascadeLayout); try { mHorizontalSpacing = a.getDimensionPixelSize( R.styleable.CascadeLayout_horizontal_spacing, getResources().getDimensionPixelSize( R.dimen.cascade_horizontal_spacing)); mVerticalSpacing = a.getDimensionPixelSize( R.styleable.CascadeLayout_vertical_spacing, getResources() .getDimensionPixelSize(R.dimen.cascade_vertical_spacing)); } finally { a.recycle(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getPaddingLeft(); int height = getPaddingTop(); int verticalSpacing; final int count = getChildCount(); for (int i = 0; i < count; i++) { verticalSpacing = mVerticalSpacing; View child = getChildAt(i); measureChild(child, widthMeasureSpec, heightMeasureSpec); LayoutParams lp = (LayoutParams) child.getLayoutParams(); width = getPaddingLeft() + mHorizontalSpacing * i; lp.x = width; lp.y = height; if (lp.verticalSpacing >= 0) { verticalSpacing = lp.verticalSpacing; } width += child.getMeasuredWidth(); height += verticalSpacing; } width += getPaddingRight(); height += getChildAt(getChildCount() - 1).getMeasuredHeight() + getPaddingBottom(); setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.layout(lp.x, lp.y, lp.x + child.getMeasuredWidth(), lp.y + child.getMeasuredHeight()); } } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams; } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p.width, p.height); } public static class LayoutParams extends ViewGroup.LayoutParams { int x; int y; public int verticalSpacing; public LayoutParams(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CascadeLayout_LayoutParams); try { verticalSpacing = a .getDimensionPixelSize( R.styleable.CascadeLayout_LayoutParams_layout_vertical_spacing, -1); } finally { a.recycle(); } } public LayoutParams(int w, int h) { super(w, h); } }}
工程目錄結構:
(原文地址:http://blog.csdn.net/vector_yi/article/details/24415537)