Android 自定义 View 之入门篇

读前思考

学习一门技术或者看一篇文章最好的方式就是带着问题去学习,这样才能在过程当中有茅塞顿开、灯火阑珊的感受,记忆也会更深入。java

  1. 如何实现自定义 View?
  2. MeasureSpec 是什么?有什么做用?
  3. 如何自定义属性值?
  4. 不一样构造方法的做用?

1. 概述

何时会用到自定义 View?在咱们的平常开发中,可能会遇到一些界面、控件没法用 Android 系统内置的 View 来完成的,这时候就须要咱们使用自定义 View 来进行绘制了。android

自定义 View 这东西不少人会比较畏惧,若是你认为他比较难,关键仍是缺乏实践写得少;若是你认为很简单,那多是你没有遇到过那些奇葩的效果,须要高等数学和各类算法。git

如今咱们就一块儿敲开自定义 View 的大门,揭开它的神秘面纱,也许你就会发现,其实它并不可怕。github

2. 了解自定义 View 的方法

本文主要作入门级别讲解,当然不会太复杂,自定义 View 的时候,主要重写两个方法算法

onMeasure():用于测量,你的控件占多大的地方由这个方法指定;canvas

onMeasure( )方法中有两个参数,widthMeasureSpec 和 heightMeasureSpec,能够经过以下代码获取模式和大小bash

//获取高度模式
int height_mode = MeasureSpec.getMode(heightMeasureSpec);
//获取宽度模式
int with_mode = MeasureSpec.getMode(widthMeasureSpec);
//获取高度尺寸
int height_size = MeasureSpec.getSize(heightMeasureSpec);
//获取宽度尺寸
int width_size = MeasureSpec.getSize(widthMeasureSpec);
复制代码

测量模式的话,有下面三种app

  • UNSPECIFIED:任意大小,想要多大就多大,尽量大,通常咱们不会遇到,如 ListView,RecyclerView,ScrollView 测量子 View 的时候给的就是 UNSPECIFIED ,通常开发中不须要关注它;ide

  • EXACTLY:一个肯定的值,好比在布局中你是这样写的 layout_width="100dp","match_parent","fill_parent";函数

  • AT_MOST:包裹内容,好比在布局中你是这样写的 layout_width="wrap_content"。

onDarw():用于绘制,你的控件呈现给用户长什么样子由这个方法决定;

onDarw( ) 方法中有个参数 Canvas,Canvas 就是咱们要在上面绘制的画布,咱们可使用咱们的画笔在上面进行绘制,最后呈现给用户。

3. 实现自定义 View

接下来咱们就动手实现一个简单的自定义 View,重在讲解实现自定义 View 的过程。

  1. 新建类继承 View,不须要指定 style 的话,建立两个构造函数便可,重写 onMeasure( ) 和 onDraw( ) 方法。
public class ViewProperty extends View {
    /**
     *在java代码建立视图的时候被调用,
     *若是是从xml填充的视图,就不会调用这个
     */
    public ViewProperty(Context context) {
        super(context);
    }
    /**
     * 这个是在xml建立可是没有指定style的时候被调用
     */
    public ViewProperty(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

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

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

}
复制代码
  1. 添加自定义属性。在 res/values/styles 文件下添加自定义属性,若是没有此文件,则新建便可。
<!-- 这里自定义了两个属性,一个是默认大小,一个是背景颜色-->
<declare-styleable name="ViewProperty">
    <attr name="default_size" format="dimension"/>
    <attr name="backgroundColor" format="color"/>
</declare-styleable>
复制代码
  1. 在两个参数的构造函数中获取属性,并进行画笔初始化
public ViewProperty(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    
    //经过 TypedArray 获取自定义属性,使用完后记得及时回收
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ViewProperty);
    mSize = array.getDimensionPixelSize(R.styleable.ViewProperty_default_size, 10);
    mColor = array.getColor(R.styleable.ViewProperty_backgroundColor, Color.RED);
    array.recycle();

    //初始化画笔
    mPaint = new Paint();
    mPaint.setColor(mColor);
    }
复制代码
  1. onMeasure( )方法中作具体测量操做
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = 100;
    int width = 100;
    //获取宽高的测量模式及具体尺寸
    int height_mode = MeasureSpec.getMode(heightMeasureSpec);
    int with_mode = MeasureSpec.getMode(widthMeasureSpec);
    int height_size = MeasureSpec.getSize(heightMeasureSpec);
    int width_size = MeasureSpec.getSize(widthMeasureSpec);
    //根据具体测量模式来给定不一样的尺寸
    if (height_mode == MeasureSpec.AT_MOST) {
        height = Dp2Px(getContext(),100);
    } else if (height_mode == MeasureSpec.EXACTLY) {
        height = height_size;
    }
    if (with_mode == MeasureSpec.AT_MOST) {
        width = Dp2Px(getContext(),100);
    } else if (with_mode == MeasureSpec.EXACTLY) {
        width = width_size;
    }
    //调用setMeasuredDimension()方法,传入测量后的尺寸值
    setMeasuredDimension(width, height);

    }
复制代码
  1. 在 onDraw( ) 方法中作具体绘制工做
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //这里绘制一个矩形
    //传入左、上、右、下坐标及画笔
    canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
}

/**
*下面是两个工具类,用于 dp 和 px 的转换,
* 因为代码中使用的是 px,布局中尺寸通常使用 dp,
* 因此须要作个转换
*/
public static int Px2Dp(Context context, int px) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px, context.getResources().getDisplayMetrics());
}
public static int Dp2Px(Context context, int dpi) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpi, context.getResources().getDisplayMetrics());
}
复制代码

4. 展现自定义 View

先 Rebuild 的一下项目,让编译器识别自定义 View,而后在布局中引用

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.keven.jianshu.part3.ShowActivity">
    <com.keven.jianshu.part3.ViewProperty
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:backgroundColor="@color/colorAccent"/>
</android.support.constraint.ConstraintLayout>
复制代码

显示效果

所有代码见 GitHub 地址
github.com/keven0632/J…

文章已经读到末尾了,不知道最初的几个问题你都会了吗?若是不会的话?能够再针对不会的问题进行精读哦!答案都在文中,相信你确定能够解决的!

相关文章
相关标签/搜索