1.protected void onAttachedToWindow ()
这个方法是在组件附加到窗口时调用的,此时它有个界面然后会进行绘画。注意这个方法是确保在 onDraw() 方法前调用的。然而它也可以在第一次onDraw() 前的任意时间内被调用,包括在onMeasure() 方法调用之前。
利用这个特性,我们可以在这个方法里执行多线程来使我们自定义组件可动态。
public void start(){
if(running == false){
//这是一个模拟时钟转动的线程
running = true;
Thread t = new Thread(new TimerTask());
t.start();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
//在这个方法中启动,指针就会不停转动下去
start();
}
时钟线程的详细过程可翻看我另一篇博客:谈谈安卓自定义组件及其操控
2.protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
这个方法是用来测量视图和它的内容来决定测量宽度和高度,通过调用measure(int, int),并由子类来重写此方法来对内容提供精确高效的测量。
规约:当重写这个方法时,你必须在最后调用setMeasuredDimension(int, int)来保存测量的视图宽度和高度。如果它失败了就会触发 IllegalStateException,由measure(int, int)抛出异常。
基类实现测量默认是以背景大小的,除非一个更大的尺寸可允许MeasureSpec值。子类应该重写onMeasure(int, int) 方法来提供更好内容尺寸。
如果这个方法被重写,子类的义务是要确保测量的宽度和高度至少是视图的宽度和高度最小值。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureSpecResult(widthMeasureSpec,"width");
int height = measureSpecResult(heightMeasureSpec,"height");
setMeasuredDimension(width,height);
}
private int measureSpecResult(int measureValue,String measureStyle){
int result = 0;
int specMode = MeasureSpec.getMode(measureValue);
int specSize = MeasureSpec.getSize(measureValue);
switch(measureStyle){
case "width":
if((specMode == MeasureSpec.EXACTLY)||(specSize == MeasureSpec.AT_MOST)){
result = 3*specSize;
}else{
result = 3*this.getResources().getDisplayMetrics().widthPixels;
}
break;
case "height":
if((specMode == MeasureSpec.EXACTLY)||(specSize == MeasureSpec.AT_MOST)){
result = specSize;
}else{
result = 256;
}
}
return result;
}
更多重要方法会后续补充介绍。