前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android 自定义控件那些事

android 自定义控件那些事

作者头像
xiangzhihong
发布2018-02-06 11:18:23
6670
发布2018-02-06 11:18:23
举报
文章被收录于专栏:向治洪向治洪

概述

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

View树

首先看一下Android视图的组成结构:

这里写图片描述
这里写图片描述

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

measure

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

代码语言:javascript
复制
getChildMeasureSpec(parentHeightMeasure,mPaddingTop+mPaddingBottom,lp.height)

Layout

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

代码语言:javascript
复制
child.layout(left,top,left+width,top+height)

自定义View

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

这里写图片描述
这里写图片描述

自定义View的步骤:

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

需要覆写的方法

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

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

代码语言:javascript
复制
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():

代码语言:javascript
复制
@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()
        );

    }
代码语言:javascript
复制
@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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
    • View树
      • measure
      • Layout
      • 需要覆写的方法
      • 其他需要注意的方法
  • 自定义View
  • 自定义ViewGroup
    • 自定义ViewGroup例子
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档