Android 自定義ViewGroup

ViewGroup是View的容器類,裏面會包含多個View。經常用的LinearLayout,RelativeLayout等都是ViewGroup的子類。

還是從方法開始說明ViewGroup,Android 自定義View(二)函數分析 中已經有說明了一下方法函數的意思,ViewGroup的實現方法有必要的兩個 onMeasure 和 onLayout 和自定義View的不同的是:

onDraw在自定義ViewGroup是,一般是調用了子類的onDraw方法,ViewGroup是View的容器,本身一般不需要draw額外的修飾,所以往往在onDraw方法裏面,只需要調用ViewGroup的onDraw默認實現方法即可。(自定義View時onLayout是空方法,ViewGroup是onLayout卻是必須實現的)

  1. onMeasure
    Measure過程還是測量ViewGroup的大小,如果layout_widht和layout_height是match_parent或具體的dp大小,直接調用setMeasuredDimension()方法,設置ViewGroup的寬高即可,如果是wrap_content,我們需要遍歷所有的子View,然後對每個子View進行測量,然後根據子View的排列規則,計算出最終ViewGroup的大小。

  2. onLayout
    layout過程其實就是對子View的位置進行排列,onLayout方法給我一個機會,來按照我們想要的規則自定義子View排列。

一個簡單的栗子(ViewGroup 中的 View 排成一列)看下 onMeasure 和 onLayout 的代碼實現:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);

    }
@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int height = 0;
        View child;
        for(int i = 0,size = getChildCount();i < size;i++) {
            child = getChildAt(i);
            child.layout(0, height, child.getMeasuredWidth(),height +  child.getMeasuredHeight());
            height += child.getMeasuredHeight();

        }
    }

要實現View一列顯示,然後每個子View的寬度是一樣的,並且每個子View的left和right是一樣的。所以每個子View只有top和bottom不一樣。我們首先定義個高度height初始爲0,然後得到所有子View的個數,依次設置每個子View的top和bottom。top就是定義的height,bottom則爲height加上子View的高度。設置完後height累加。

LayoutParams

LayoutParams存儲了子View在加入ViewGroup中時的一些參數信息,在繼承ViewGroup類時,一般也需要新建一個新的LayoutParams類,就像SDK中我們熟悉的LinearLayout.LayoutParams,RelativeLayout.LayoutParams類等一樣,那麼可以這樣做,在你定義的ViewGroup子類中,新建一個LayoutParams類繼承與ViewGroup.LayoutParams。實際使用:

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

實例應用

自定義一個根據屏幕寬度自動換行的ViewGroup:

public class LineBreakLayout extends ViewGroup implements View.OnClickListener {
    private final static int VIEW_MARGIN = 2;
    private int widthMargin = VIEW_MARGIN;//view width space
    private int heightMargin = VIEW_MARGIN;//view height space
    private LineLayoutItemListener mListener;

    public LineBreakLayout(Context context) {
        super(context);
    }

    public LineBreakLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public LineBreakLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setViewMargin(int widthMargin, int heightMargin) {
        this.widthMargin = widthMargin;
        this.heightMargin = heightMargin;
    }

    public void setOnLineLayoutItemListener(LineLayoutItemListener listener) {
        mListener = listener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //得到ViewGroup的初始寬高
        final int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec) + getPaddingBottom()+getPaddingTop();
        int line_height = 0;
        //獲取第一個子View的起始點位置
        int xpos = getPaddingLeft();
        int ypos = getPaddingTop();
        //計算每一個子View的尺寸,並算出ViewGroup的高度
        for (int index = 0; index < getChildCount(); index++) {
            final View child = getChildAt(index);
            if (child.getVisibility() == GONE) {
                continue;
            }
            child.setId(index);
            child.setOnClickListener(this);
            final LayoutParams lp = child.getLayoutParams();
            //算出子View寬的MeasureSpec值
            int wSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.UNSPECIFIED);
            //算出子View高的MeasureSpec值
            int hSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.UNSPECIFIED);
            //讓子View記住自己寬高的MeasureSpec值,子View的
            //函數傳入的就是這裏算出來的這兩個值
            child.measure(wSpec, hSpec);
            //設置完MeasureSpec值後調用View.getMeasuredWidth()函數算出View的寬度
            final int childw = child.getMeasuredWidth();
            //記錄最大行高(子View的高度有可能不一樣,行高取最大高度)
            line_height = Math.max(line_height, child.getMeasuredHeight() + heightMargin);
            if (xpos + childw + widthMargin > width) {
                //初始座標的x偏移值+子View寬度>ViewGroup寬度 就換行
                xpos = getPaddingLeft();//座標x偏移值歸零
                ypos += line_height;    //座標y偏移值再加上本行的行高也就是換行
            }
            //算出下一個子View的起始點x偏移值
            xpos += childw + widthMargin;
        }
        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
            //對高度期望值沒有限制
            height = ypos + line_height + heightMargin;
        } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            //達不到指定高度則縮小高度
            if (ypos + line_height < height) {
                height = ypos + line_height + heightMargin;
            }
        } else {
            height = ypos + line_height + heightMargin;
        }
        //設置ViewGroup寬高值
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int count = getChildCount();
        int parentWidth = right - left;
        top = 0;//clear top distance
        int row = 0;// which row lay you view relative to parent
        int lengthX = 0; // right position of child relative to parent
        int lengthY = top; // bottom position of child relative to parent
        //計算每一個子View的尺寸,並算出ViewGroup的高度
        for (int i = 0; i < count; i++) {
            final View child = this.getChildAt(i);
            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();
            lengthX += width + widthMargin;
            lengthY = row * (height + heightMargin) + heightMargin + height + top;
            // if it can't drawing on a same line , skip to next line
            if (lengthX > parentWidth) {
                lengthX = width + widthMargin;
                row ++;
                lengthY = row * (height + heightMargin) + heightMargin + height + top;
            }
            child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
        }
    }

    @Override
    public void onClick(View v) {
        if (mListener != null) {
            int position = v.getId();
            mListener.onLineItemClick(this, v, position);
        }
    }

    public interface LineLayoutItemListener {
        void onLineItemClick(ViewGroup parent, View view, int position);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章