android 自定义控件那些事

来源:互联网 发布:流量龙卷风淘宝 编辑:程序博客网 时间:2024/05/17 22:22

概述

在android应用开发过程中,固定的一些控件和属性可能满足不了开发的需求,所以在一些特殊情况下,我们需要自定义控件与属性。而自定义控件通常有两种:自定义View和自定义ViewGroup。

View树

首先看一下Android视图的组成结构:
这里写图片描述

View树的绘制原理:树的遍历是有序的,由父视图到子视图,每一个 ViewGroup 负责测绘它所有的子视图,而最底层的 View 会负责测绘自身。

measure

树的遍历遵循由父视图到子视图,测量过程也遵循这个过程。通过getChildMeasureSpec获取ChildView的MeasureSpec,回调ChildView.measure最终调用setMeasuredDimension得到ChildView的尺寸:

getChildMeasureSpec(parentHeightMeasure,mPaddingTop+mPaddingBottom,lp.height)

Layout

同测量一样也是自上而下进行遍历的,该方法计算每个ChildView的ChildLeft,ChildTop;与measure中得到的每个ChildView的mMeasuredWidth 和 mMeasuredHeight,来对ChildView进行布局。

child.layout(left,top,left+width,top+height)

自定义View

我们首先来看一下Android的View的绘制流程:

这里写图片描述

自定义View的步骤:

  • 继承View类或其子类,并覆写其中的一些方法。
  • 为自定义View类增加属性,并添加一些响应事件

需要覆写的方法

我们通常需要对onMeasure(),onLayout(),onDraw()进行覆写。

onMeasure()
用于计算视图大小(即长和宽)的方式,并通过setMeasuredDimension(width, height)保存计算结果。

protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),        getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));}

onLayout()
为viewGroup类型布局子视图用的,在View中这个函数为空函数。

onDraw()
view中onDraw()是个空函数,也就是说具体的视图都要覆写该函数来实现自己的绘制。对于ViewGroup则不需要实现该函数,因为作为容器是“没有内容“的(但必须实现dispatchDraw()函数,告诉子view绘制自己)。

其他需要注意的方法

  • onKeyUp(): 当松开某个键盘时
  • onTrackballEvent(): 当发生轨迹球事件时
  • onSizeChange(): 当该组件的大小被改变时
  • onFinishInflate():回调方法,当应用从XML加载该组件并用它构建界面之后调用的方法
  • onWindowFocusChanged(boolean): 当该组件得到、失去焦点时
  • onAttachedToWindow(): 当把该组件放入到某个窗口时
  • onDetachedFromWindow():当把该组件从某个窗口上分离时触发的方法
  • onWindowVisibilityChanged(int): 当包含该组件的窗口的可见性发生改变时触发的方法

关于例子,这里就不多详述了。

自定义ViewGroup

在讲解如何操作自定义ViewGroup之前我们来看看自定义ViewGroup的流程图:
这里写图片描述

在自定义ViewGroup中尝尝需要覆写onMeasure()和onLayout()等方法,这里不做过多解释,这里说一下其他的一些常用方法。

dispatchDraw()
View 中这个函数是一个空函数,ViewGroup 复写了dispatchDraw()来对其子视图进行绘制。自定义的 ViewGroup 一般不对dispatchDraw()进行复写。

requestLayout()
当布局变化的时候,比如方向变化,尺寸的变化,会调用该方法,在自定义的视图中,如果某些情况下希望重新测量尺寸大小,应该手动去调用该方法,它会触发measure()和layout()过程,但不会进行 draw。

自定义ViewGroup例子

如我们要实现一个自定义的换行的控件:
这里写图片描述

onMeasure():

@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);        int width = 0;        int height = 0;        int lineWidth = 0;        int lineHeight = 0;        int cCount = getChildCount();        for (int i = 0; i < cCount; i++)        {            View child = getChildAt(i);            measureChild(child, widthMeasureSpec, heightMeasureSpec);            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;            int childHeight = child.getMeasuredHeight() + lp.topMargin+ lp.bottomMargin;            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight())            {                width = Math.max(width, lineWidth);                lineWidth = childWidth;                height += lineHeight;                lineHeight = childHeight;            } else{                lineWidth += childWidth;                lineHeight = Math.max(lineHeight, childHeight);            }            if (i == cCount - 1)            {                width = Math.max(lineWidth, width);                height += lineHeight;            }        }        setMeasuredDimension(                modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width + getPaddingLeft() + getPaddingRight(),                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height + getPaddingTop()+ getPaddingBottom()        );    }
@Override    protected void onLayout(boolean changed, int l, int t, int r, int b) {        mAllViews.clear();        mLineHeight.clear();        int width = getWidth();        int lineWidth = 0;        int lineHeight = 0;        List<View> lineViews = new ArrayList<View>();        int cCount = getChildCount();        for (int i = 0; i < cCount; i++)        {            View child = getChildAt(i);            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();            int childWidth = child.getMeasuredWidth();            int childHeight = child.getMeasuredHeight();            if (lineWidth + childWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()) {                mLineHeight.add(lineHeight);                mAllViews.add(lineViews);                lineWidth = 0;                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;                lineViews = new ArrayList<View>();            }                lineWidth += childWidth + lp.leftMargin + lp.rightMargin;                lineHeight = Math.max(lineHeight, childHeight + lp.topMargin+ lp.bottomMargin);                lineViews.add(child);        }        mLineHeight.add(lineHeight);        mAllViews.add(lineViews);        int left = getPaddingLeft();        int top = getPaddingTop();        int lineNum = mAllViews.size();        for (int i = 0; i < lineNum; i++)        {            lineViews = mAllViews.get(i);            lineHeight = mLineHeight.get(i);            for (int j = 0; j < lineViews.size(); j++)            {                View child = lineViews.get(j);                // 判断child的状态                if (child.getVisibility() == View.GONE)                {                    continue;                }                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();                int lc = left + lp.leftMargin;                int tc = top + lp.topMargin;                int rc = lc + child.getMeasuredWidth();                int bc = tc + child.getMeasuredHeight();                // 为子View进行布局                child.layout(lc, tc, rc, bc);                left += child.getMeasuredWidth() + lp.leftMargin+ lp.rightMargin;            }            left = getPaddingLeft() ;            top += lineHeight ;        }    }

完整的实例:http://download.csdn.net/detail/xiangzhihong8/9788465

2 0
原创粉丝点击