教你搞定Android自定义ViewGroup
ViewGroup
我們知道ViewGroup就是View的容器類(lèi),我們經(jīng)常用的LinearLayout,RelativeLayout等都是ViewGroup的子類(lèi),因?yàn)閂iewGroup有很多子View,所以它的整個(gè)繪制過(guò)程相對(duì)于View會(huì)復(fù)雜一點(diǎn),但是還是三個(gè)步驟measure,layout,draw,我們一次說(shuō)明。
-  Measure @Override protected 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();} }
 Measure過(guò)程還是測(cè)量ViewGroup的大小,如果layout_widht和layout_height是match_parent或具體的xxxdp,就很簡(jiǎn)答了,直接調(diào)用setMeasuredDimension()方法,設(shè)置ViewGroup的寬高即可,如果是wrap_content,就比較麻煩了,我們需要遍歷所有的子View,然后對(duì)每個(gè)子View進(jìn)行測(cè)量,然后根據(jù)子View的排列規(guī)則,計(jì)算出最終ViewGroup的大小。你可能需要類(lèi)似上面的代碼,其中g(shù)etChildCount()方法,返回子View的數(shù)量,measureChild()方法,調(diào)用子View的測(cè)量方法。 
- Layout
 上一篇中,我們稍微提到了,layout過(guò)程其實(shí)就是對(duì)子View的位置進(jìn)行排列,onLayout方法給我一個(gè)機(jī)會(huì),來(lái)按照我們想要的規(guī)則自定義子View排列。 @Override protected 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);} } 你同樣可能需要類(lèi)似上面的代碼,其中child.layout(left,top,right,bottom)方法可以對(duì)子View的位置進(jìn)行設(shè)置,四個(gè)參數(shù)的意思大家通過(guò)變量名都應(yīng)該清楚了。
-  Draw 
 ViewGroup在draw階段,其實(shí)就是按照子類(lèi)的排列順序,調(diào)用子類(lèi)的onDraw方法,因?yàn)槲覀冎皇荲iew的容器, 本身一般不需要draw額外的修飾,所以往往在onDraw方法里面,只需要調(diào)用ViewGroup的onDraw默認(rèn)實(shí)現(xiàn)方法即可。LayoutParamsViewGroup還有一個(gè)很重要的知識(shí)LayoutParams,LayoutParams存儲(chǔ)了子View在加入ViewGroup中時(shí)的一些參數(shù)信息,在繼承ViewGroup類(lèi)時(shí),一般也需要新建一個(gè)新的LayoutParams類(lèi),就像SDK中我們熟悉的LinearLayout.LayoutParams,RelativeLayout.LayoutParams類(lèi)等一樣,那么可以這樣做,在你定義的ViewGroup子類(lèi)中,新建一個(gè)LayoutParams類(lèi)繼承與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);}}那么現(xiàn)在新的LayoutParams類(lèi)已經(jīng)有了,如何讓我們自定義的ViewGroup使用我們自定義的LayoutParams類(lèi)來(lái)添加子View呢,ViewGroup同樣提供了下面這幾個(gè)方法供我們重寫(xiě),我們重寫(xiě)返回我們自定義的LayoutParams對(duì)象即可。 @Override public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {return new NinePhotoView.LayoutParams(getContext(), attrs); }@Override protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {return new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); }@Override protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {return new LayoutParams(p); }@Override protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {return p instanceof NinePhotoView.LayoutParams; }實(shí)例我們還是做一個(gè)實(shí)例來(lái)說(shuō)明,我們今天做一個(gè)類(lèi)似微信朋友圈 存儲(chǔ)要發(fā)送圖片的控件,點(diǎn)擊+號(hào)圖片,可以一直加圖片,最多9張。那么微信是4個(gè)一排,我們這里是3個(gè)一排,因?yàn)橐话愠R?guī)都是三個(gè)一排,這些都是細(xì)節(jié)不要在意(另外偷偷告訴大家,微信的實(shí)現(xiàn)是用TableLayout,-.-)。 
 微信朋友圈發(fā)送圖片 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 views int hSpace = Utils.dpToPx(10, getResources()); // vertical space among children views int vSpace = Utils.dpToPx(10, getResources());// every child view width and height. int childWidth = 0; int childHeight = 0;// store images res id ArrayList<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()); }目前為止,都跟上一篇說(shuō)的大致差不多,另外拍照和從相冊(cè)選擇圖片不是我們這一篇的重點(diǎn),所以我們把圖片硬編碼到代碼中(全是美女...),ViewGroup初始化時(shí)我們添加了一個(gè)+號(hào)按鈕,給用戶(hù)點(diǎn)擊添加新的圖片。 
-  Measure @Override protected 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三個(gè)一排,而且都是正方形,所以我們上面通過(guò)循環(huán)很好去得到所有子View的位置,注意我們上面把子View的左上角坐標(biāo)存儲(chǔ)到我們自定義的LayoutParams 的left和top二個(gè)字段中,Layout階段會(huì)使用,最后我們算得整個(gè)ViewGroup的寬高,調(diào)用setMeasuredDimension設(shè)置。 
-  Layout @Override protected 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() {@Overridepublic 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() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {addPhoto();}});builder.show(); }最核心的就是調(diào)用layout方法,根據(jù)我們measure階段獲得的LayoutParams中的left和top字段,也很好對(duì)每個(gè)子View進(jìn)行位置排列。然后判斷在圖片未達(dá)到最大值9張時(shí),默認(rèn)最后一張是+號(hào)圖片,然后設(shè)置點(diǎn)擊事件,彈出對(duì)話框供用戶(hù)選擇操作。 
- Draw
 不需要重寫(xiě),使用ViewGroup默認(rèn)實(shí)現(xiàn)即可。附上布局文件
最后還是加上程序運(yùn)行的效果圖,今天自定義ViewGroup的講解就這么多了,祝大家每天都有新收獲,每天都有好心情~~~
NiewPhotoView.gif
總結(jié)
以上是生活随笔為你收集整理的教你搞定Android自定义ViewGroup的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 实践自定义UI—RLF...(Relat
- 下一篇: Android 利用addView 动态
