日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

教你搞定Android自定义ViewGroup

發布時間:2025/6/15 Android 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 教你搞定Android自定义ViewGroup 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ViewGroup

我們知道ViewGroup就是View的容器類,我們經常用的LinearLayout,RelativeLayout等都是ViewGroup的子類,因為ViewGroup有很多子View,所以它的整個繪制過程相對于View會復雜一點,但是還是三個步驟measure,layout,draw,我們一次說明。

  • Measure
    Measure過程還是測量ViewGroup的大小,如果layout_widht和layout_height是match_parent或具體的xxxdp,就很簡答了,直接調用setMeasuredDimension()方法,設置ViewGroup的寬高即可,如果是wrap_content,就比較麻煩了,我們需要遍歷所有的子View,然后對每個子View進行測量,然后根據子View的排列規則,計算出最終ViewGroup的大小。

    @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();} }

    你可能需要類似上面的代碼,其中getChildCount()方法,返回子View的數量,measureChild()方法,調用子View的測量方法。

  • Layout
    上一篇中,我們稍微提到了,layout過程其實就是對子View的位置進行排列,onLayout方法給我一個機會,來按照我們想要的規則自定義子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);} } 你同樣可能需要類似上面的代碼,其中child.layout(left,top,right,bottom)方法可以對子View的位置進行設置,四個參數的意思大家通過變量名都應該清楚了。
  • Draw
    ViewGroup在draw階段,其實就是按照子類的排列順序,調用子類的onDraw方法,因為我們只是View的容器, 本身一般不需要draw額外的修飾,所以往往在onDraw方法里面,只需要調用ViewGroup的onDraw默認實現方法即可。

    LayoutParams

    ViewGroup還有一個很重要的知識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對象即可。

    @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; }

    實例

    我們還是做一個實例來說明,我們今天做一個類似微信朋友圈 存儲要發送圖片的控件,點擊+號圖片,可以一直加圖片,最多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 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()); }

    目前為止,都跟上一篇說的大致差不多,另外拍照和從相冊選擇圖片不是我們這一篇的重點,所以我們把圖片硬編碼到代碼中(全是美女...),ViewGroup初始化時我們添加了一個+號按鈕,給用戶點擊添加新的圖片。

  • 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三個一排,而且都是正方形,所以我們上面通過循環很好去得到所有子View的位置,注意我們上面把子View的左上角坐標存儲到我們自定義的LayoutParams 的left和top二個字段中,Layout階段會使用,最后我們算得整個ViewGroup的寬高,調用setMeasuredDimension設置。

  • 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(); }

    最核心的就是調用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.NinePhotoViewandroid: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.gif

總結

以上是生活随笔為你收集整理的教你搞定Android自定义ViewGroup的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。