浅析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>

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

节点里的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().
- onTouchEvent
- onInterceptTouchEvent(ViewGroup)
手势控制和事件分发在本章不是重点,但是有些自定义控件中需要有与用户交互的功能。有需要的朋友可以去看看Android事件分发机制详解:史上最全面、最易懂。写的非常详细。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值