浅析Android自定义view

为什么要自定义view?

  • 在android给我们提供的view(textview,imageview等) 上添加新的功能
  • 处理特有的用户交互
  • 当android给我们提供的view不足以满足我们的需求,如瀑布流布局,粘性动画等,就需要自己去定义view 了
  • 熟练掌握自定义控件后,就可以实现各种酷炫的效果了。装x必备

自定义view的一般步骤

  • 自定义属性的声明与获取
    首先需要在res/values/attrs.xml定义声明,我用的是as,默认是没有这个xml文件的,需要我们自己去创建
image.png
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="image" format="reference"/>
        <attr name="color" format="color"/>
        <attr name="text" format="string"/>
        <attr name="text_size" format="integer"/>
    </declare-styleable>
</resources>

在布局中引用自定义属性

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:zsy="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zsy.demo.stickyview.MainActivity">
    <com.zsy.demo.stickyview.CustomView
        android:layout_width="100dp"
        android:layout_height="100dp"
        zsy:text="hello,world!"
        zsy:text_size="9527"
        />
</RelativeLayout>

注意<declare-styleable>节点中的name在as中必须与你的自定义控件类名一致,否则命名空间是找不到该属性的。(亲测)


image.png

<attr>节点里的name是给自定义属性命名的,format是给自定义的属性定义一个类型,如:
-string 字符串类型
-integer 整形
-color 颜色类型
-reference 引用类型
...
之后在view的构造方法中进行获取:

public class CustomView extends View {
    private static final String TAG = "CustomView";
    private BitmapDrawable mBitmap;
    private int mColor;
    private String mText;
    private int mTextInteger;

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

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.CustomView);
        int count = a.getIndexCount();
        for (int i = 0; i < count; i++)
        {
            int attr = a.getIndex(i);
            switch (attr)
            {
                case R.styleable.CustomView_image:
                    mBitmap = (BitmapDrawable) a.getDrawable(attr);
                    break;
                case R.styleable.CustomView_color:
                    mColor = a.getColor(attr, 0xFF45C01A);
                    break;
                case R.styleable.CustomView_text:
                    mText = a.getString(attr);
                    Log.d(TAG, mText);
                    break;
                case R.styleable.CustomView_text_size:
                    mTextInteger =   a.getInteger(attr,-1);
                    Log.d(TAG, String.valueOf(mTextInteger));
                    break;
            }
        }
        //获取完属性之后一定要recycle
        a.recycle();
    }
}

打印结果为

image.png
  • 测量onMeasure
    控件通过测量决定自身到底需要多少宽高
 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

参数MeasureSpec可以理解为测量规格,它代表一个32位int值,高2位代表SpecMode,低30位代表SpecSize,SpecMode是指测量模式,SpecSize是指在某种测量模式下的规格大小。

下面得到宽高的测量模式和测量大小

  // 宽度测量模式及测量宽度
int widthMeasureModle = MeasureSpec.getMode(widthMeasureSpec);
int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
 // 高度测量模式及测量高度
int heightMeasureModle = MeasureSpec.getMode(heightMeasureSpec);
int measureHeight = MeasureSpec.getSize(heightMeasureSpec);

测量模式分为三种:

EXACTLY : 给当前控件设置了明确的值,如100dp,match_parent等,这个时候view的最终大小就是SpecSize所指定的值
AT_MOST :父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值。具体是什么值要看不同的view的具体表现。如 warp_content
UNSPECIFIED:父容器不对view有任何限制,要多大给多大。如listview,scrollview

下面给出一段伪代码:

if (widthMeasureModle == MeasureSpec.EXACTLY){
            width = measureWidth;
        }else if (widthMeasureModle == MeasureSpec.AT_MOST){
            width = Math.min(200,measureWidth);
        }else {
            //TODO
        }
//设置宽高
setMeasuredDimension(measureWidth,measureHeight);

ViewGroup的测量和View的测量差不多,只是它除了完成自己的measure过程之外,还会遍历去调用所有子元素的measure方法,各个子元素再递归去执行这个过程。这里可以通过源码看出来:

    protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();
        //创建子元素的MeasureSpec
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);
       //这里调用了子元素的测量方法
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[I];
            //遍历所有子元素,然后测量其高度
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

requestLayout()方法可以重新测量

  • 布局onLayout(ViewGroup)
@Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

onLayout比较简单,是将所有子元素进行布局。在自定义view中一般用不到该方法。 requestLayout()方法可以重新布局。
参数changed表示view有新的尺寸或位置;
参数left表示相对于父view的Left位置;
参数top表示相对于父view的Top位置;
参数right表示相对于父view的Right位置;
参数bottom表示相对于父view的Bottom位置。

  • 绘制onDraw
@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

利用canvas可以绘制出任意你想要的形状,组合canvas可以实现复杂的效果。在这里就不多说啦。
调用invalidate()在主线程中刷新画布,子线程中调用postInvalidate().

知识在于积累,源于分享。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容