標籤:
教你搞定Android自訂ViewGroup http://www.jianshu.com/p/138b98095778字數1794 閱讀7030 評論8 喜歡37上一篇我們介紹了Android中自訂View的知識,並實現了一個類似Google彩虹進度條的自訂View,今天我們將進一步學習如何去自訂一個ViewGroup。ViewGroup我們知道ViewGroup就是View的容器類,我們經常用的LinearLayout,RelativeLayout等都是ViewGroup的子類,因為ViewGroup有很多子View,所以它的整個繪製過程相對於View會複雜一點,但是還是三個步驟measure,layout,draw,我們一次說明。MeasureMeasure過程還是測量ViewGroup的大小,如果layout_widht和layout_height是match_parent或具體的xxxdp,就很簡答了,直接調用setMeasuredDimension()方法,設定ViewGroup的寬高即可,如果是wrap_content,就比較麻煩了,我們需要遍曆所有的子View,然後對每個子View進行測量,然後根據子View的排列規則,計算出最終ViewGroup的大小。@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); this.measureChild(child, widthMeasureSpec, heightMeasureSpec); int cw = child.getMeasuredWidth(); // int ch = child.getMeasuredHeight(); }}你可能需要類似上面的代碼,其中getChildCount()方法,返回子View的數量,measureChild()方法,調用子View的測量方法。Layout上一篇中,我們稍微提到了,layout過程其實就是對子View的位置進行排列,onLayout方法給我一個機會,來按照我們想要的規則自訂子View排列。@Overrideprotected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); LayoutParams lParams = (LayoutParams) child.getLayoutParams(); child.layout(lParams.left, lParams.top, lParams.left + childWidth, lParams.top + childHeight); }}你同樣可能需要類似上面的代碼,其中child.layout(left,top,right,bottom)方法可以對子View的位置進行設定,四個參數的意思大家通過變數名都應該清楚了。DrawViewGroup在draw階段,其實就是按照子類的排列順序,調用子類的onDraw方法,因為我們只是View的容器, 本身一般不需要draw額外的修飾,所以往往在onDraw方法裡面,只需要調用ViewGroup的onDraw預設實現方法即可。LayoutParamsViewGroup還有一個很重要的知識LayoutParams,LayoutParams儲存了子View在加入ViewGroup中時的一些參數資訊,在繼承ViewGroup類時,一般也需要建立一個新的LayoutParams類,就像SDK中我們熟悉的LinearLayout.LayoutParams,RelativeLayout.LayoutParams類等一樣,那麼可以這樣做,在你定義的ViewGroup子類中,建立一個LayoutParams類繼承與ViewGroup.LayoutParams。public static class LayoutParams extends ViewGroup.LayoutParams { public int left = 0; public int top = 0; public LayoutParams(Context arg0, AttributeSet arg1) { super(arg0, arg1); } public LayoutParams(int arg0, int arg1) { super(arg0, arg1); } public LayoutParams(android.view.ViewGroup.LayoutParams arg0) { super(arg0); }}那麼現在新的LayoutParams類已經有了,如何讓我們自訂的ViewGroup使用我們自訂的LayoutParams類來添加子View呢,ViewGroup同樣提供了下面這幾個方法供我們重寫,我們重寫返回我們自訂的LayoutParams對象即可。@Overridepublic android.view.ViewGroup.LayoutParams generateLayoutParams( AttributeSet attrs) { return new NinePhotoView.LayoutParams(getContext(), attrs);}@Overrideprotected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);}@Overrideprotected android.view.ViewGroup.LayoutParams generateLayoutParams( android.view.ViewGroup.LayoutParams p) { return new LayoutParams(p);}@Overrideprotected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) { return p instanceof NinePhotoView.LayoutParams;}執行個體我們還是做一個執行個體來說明,我們今天做一個類似朋友圈 儲存要發送圖片的控制項,點擊+號圖片,可以一直加圖片,最多9張。那麼是4個一排,我們這裡是3個一排,因為一般常規都是三個一排,這些都是細節不要在意(另外偷偷告訴大家,的實現是用TableLayout,-.-)。朋友圈發送圖片朋友圈發送圖片public class NinePhotoView extends ViewGroup {public static final int MAX_PHOTO_NUMBER = 9;private int[] constImageIds = { R.drawable.girl_0, R.drawable.girl_1, R.drawable.girl_2, R.drawable.girl_3, R.drawable.girl_4, R.drawable.girl_5, R.drawable.girl_6, R.drawable.girl_7, R.drawable.girl_8 };// horizontal space among children viewsint hSpace = Utils.dpToPx(10, getResources());// vertical space among children viewsint vSpace = Utils.dpToPx(10, getResources());// every child view width and height.int childWidth = 0;int childHeight = 0;// store images res idArrayList<integer> mImageResArrayList = new ArrayList<integer>(9);private View addPhotoView;public NinePhotoView(Context context) { super(context);}public NinePhotoView(Context context, AttributeSet attrs) { this(context, attrs, 0);}public NinePhotoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.NinePhotoView, 0, 0); hSpace = t.getDimensionPixelSize( R.styleable.NinePhotoView_ninephoto_hspace, hSpace); vSpace = t.getDimensionPixelSize( R.styleable.NinePhotoView_ninephoto_vspace, vSpace); t.recycle(); addPhotoView = new View(context); addView(addPhotoView); mImageResArrayList.add(new integer());}目前為止,都跟上一篇說的大致差不多,另外拍照和從相簿選擇圖片不是我們這一篇的重點,所以我們把圖片寫入程式碼到代碼中(全是美女...),ViewGroup初始化時我們添加了一個+號按鈕,給使用者點擊添加新的圖片。Measure@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int rw = MeasureSpec.getSize(widthMeasureSpec); int rh = MeasureSpec.getSize(heightMeasureSpec); childWidth = (rw - 2 * hSpace) / 3; childHeight = childWidth; int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); //this.measureChild(child, widthMeasureSpec, heightMeasureSpec); LayoutParams lParams = (LayoutParams) child.getLayoutParams(); lParams.left = (i % 3) * (childWidth + hSpace); lParams.top = (i / 3) * (childWidth + vSpace); } int vw = rw; int vh = rh; if (childCount < 3) { vw = childCount * (childWidth + hSpace); } vh = ((childCount + 3) / 3) * (childWidth + vSpace); setMeasuredDimension(vw, vh);}我們的子View三個一排,而且都是正方形,所以我們上面通過迴圈很好去得到所有子View的位置,注意我們上面把子View的左上方座標儲存到我們自訂的LayoutParams 的left和top二個欄位中,Layout階段會使用,最後我們算得整個ViewGroup的寬高,調用setMeasuredDimension設定。Layout@Overrideprotected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { int childCount = this.getChildCount(); for (int i = 0; i < childCount; i++) { View child = this.getChildAt(i); LayoutParams lParams = (LayoutParams) child.getLayoutParams(); child.layout(lParams.left, lParams.top, lParams.left + childWidth, lParams.top + childHeight); if (i == mImageResArrayList.size() - 1 && mImageResArrayList.size() != MAX_PHOTO_NUMBER) { child.setBackgroundResource(R.drawable.add_photo); child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { addPhotoBtnClick(); } }); }else { child.setBackgroundResource(constImageIds[i]); child.setOnClickListener(null); } }}public void addPhoto() { if (mImageResArrayList.size() < MAX_PHOTO_NUMBER) { View newChild = new View(getContext()); addView(newChild); mImageResArrayList.add(new integer()); requestLayout(); invalidate(); }}public void addPhotoBtnClick() { final CharSequence[] items = { "Take Photo", "Photo from gallery" }; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { addPhoto(); } }); builder.show();}最核心的就是調用layout方法,根據我們measure階段獲得的LayoutParams中的left和top欄位,也很好對每個子View進行位置排列。然後判斷在圖片未達到最大值9張時,預設最後一張是+號圖片,然後設定點擊事件,彈出對話方塊供使用者選擇操作。Draw不需要重寫,使用ViewGroup預設實現即可。附上布局檔案<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="40dp"android:orientation="vertical" ><com.sw.demo.widget.NinePhotoView android:id="@+id/photoview" android:layout_width="match_parent" android:layout_height="wrap_content" app:ninephoto_hspace="10dp" app:ninephoto_vspace="10dp" app:rainbowbar_color="@android:color/holo_blue_bright" ></com.sw.demo.widget.NinePhotoView></LinearLayout>最後還是加上程式啟動並執行,今天自訂ViewGroup的講解就這麼多了,祝大家每天都有新收穫,每天都有好心情~~~NiewPhotoView.gifNiewPhotoView.gif
Android自訂ViewGroup (選擇照片或者拍照)