在Android的开发中,很多时候系统提供的View已经不能够满足我们的要求,自定义View的需求自然而然就出来了。
实现自定义的View,需要去继承View类,并重写其OnMeasure和OnDraw方法,从而实现我们自己想要的效果。
其本质上就是封装了一些自己想要的效果,并使之能够被Framework识别,跟普通的系统的控件一样,可以重复利用。
下面就拿一个例子开始吧,先上一张效果图:
在这里,有六个正方形的View,每一个View的背景颜色都不一样,图片也不一样,旋转的角度也不一样,其实这三个都是自定义的属性来的。
1. 自定义属性。
在 res/values/文件夹中创建一个 attrs.xml 文件,定义我们的属性。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomRotateView">
<attr name="drawable" format="reference"/>
<attr name="degree" format="float" />
<attr name="bgcolor" format="color" />
</declare-styleable>
</resources>
如上 name 是属性的名字, format 是属性对应值的类型, 其中reference 表明这个值是参考其他的资源文件,在xml 中使用这个属性的形式就是:"@drawable/photo1"
2. 定义好自定义属性之后,开始创建自定义的View。
很显然,一切得从继承View开始,代码如下:
package com.example.apidemostudy;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class CustomRotateView extends View {
private final static String tag = "com.example.apidemostudy.CustomRotateView";
private Bitmap mBitmap; // The bitmap to be drawn
private int bgColor; // the BackgroundColor
private float degree; // the angels to rotate
private Matrix matrix; // the matrix to transform
private int mWidth = 240, mHeight