在前面几篇博客了解了Android中View的绘制流程和自定义View的几个常用类,在这一篇博客中主要介绍一下Android中自定义View的基本步骤以及简单的使用自定义属性。
通常来说,自定义组件有两种定义方式:
从0开始定义自定义组件,组件类继承View;
从Android已有的组件进行扩展,定义出更加个性化或者更适合需求的控件。
Android自定义View的基本步骤:
① 对于直接继承自View的组件:
创建继承自View的自定义组件,第一步就是重写构造方法,接着就是重写onMeasure()方法进行测量和onDraw()方法绘制结果,第三步就是处理相关的事件,在这里主要说第一、二步,事件的处理可以浏览《Android中的事件分发机制》这篇博客。
以下代码我创建了一个继承自View的自定义组件,并重写了onMeasure()方法和onDraw()方法:
public class TestView extends View {
public TestView(Context context) {
super(context);
}
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TestView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 测量组件大小
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
// 绘制组件
super.onDraw(canvas);
}
}
四个构造方法
public TestView(Context context)
public TestView(Context context, AttributeSet attrs)
public TestView(Context context, AttributeSet attrs, int defStyleAttr)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TestView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
这四个构造方法的调用场景并不一样:
第一个只有一个参数,是在代码中创建组件时调用,比如创建一个按钮:Button btn = new Button(this),this是Context的子类;
第二个构造方法在layout布局文件中使用组件时调用,参数attrs表示当前配组件在xml文件中的属性集合,例如在要layout.xml中定义一个按钮:<Button android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "确定"/>,Android会调用第二个构造方法创建出Button对象;
第三个构造方法是不会自动调用的,当我们在Theme中定义了Style属性时通常在第二个构造方法中手动调用;
第四个构造方法是在Android5.0以上才加上的。
测量大小
protected void onMeasure(int widthMeasure