看完鸿洋大大的博客其中一篇关于自定义view的文章http://blog.csdn.net/lmj623565791/article/details/24252901,受益良多决定自己一试,并记录下自己的心得。关于编写自定义View的步骤,请大家阅读鸿洋大大的文章,在这里我就不再累述。
一、我们需要自定义温度计的属性,比如将温度计放入布局之后温度计和内包含液体的颜色,温度计的高低等等。在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性和声明我们的整个样式代码如下:
liquid_color : 温度计里液体的颜色
crust_color : 温度计外壳的颜色
crust_width : 温度计外壳的宽度
crust_height : 温度计外壳的高度
init_temperature : 温度计的初始温度
二、然后我们新建一个类继承View,用以实现我们的温度计。自定义组件重点是实现View类的onDraw()和onMeasure()方法,前者用于绘制组件的外观,后者用与控制组件本身的大小,这里我的组件不需太多要求,就让他全屏覆盖,所以我在放置组件时把大小都设置成了match_parent,没有往onMeasure()填充代码。
package com.thermometer.curio.thermometer;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
/**
* Created by Curio on 2016/8/20.
*/
public class MyThermometer extends View {
private int mCrustColor;
private int mLiquidColor;
private float mCrustWidth;
private float mCrustHeight;
private float mInitTemperature;
/**
* 定义温度计感温泡的位置
*/
float circleX;
float circleY;
//创建画笔
Paint p;
Paint lp;
public MyThermometer(Context context){
this(context,null);
}
public MyThermometer(Context context,AttributeSet attrs){
this(context,attrs,0);
}
/**
* 获取自定义属性