一、创建自定义控件的基本步骤
- 继承自View或View子类
- 创建两个构造方法,分别为在代码中创建对象、在布局中声明控件在代码中创建对象时调用
- 一些初始化操作initView()
- 测量大小onMeasure(int,int)
- 指定位置onLayout(boolean,int,int,int,int)
- 绘制内容onDraw(canvas)
二、一个MyView模板
public class MyView extends View{
private Paint paint;
/**
* 在代码中使用new关键字创建对象时调用
* @param context 上下文
*/
public MyView(Context context) {
super(context);
initView();
}
/**
* 在布局文件中声明该控件时,代码中调用此方法时创建对象
* @param context
* @param attrs
*/
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
/**
* 一些初始化操作
*/
private void initView(){
paint=new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true); //打开抗锯齿
}
/**
* 一个View从创建到显示到屏幕上,中间有几个步骤:
* 1.测量大小 onMeasure(int,int)
* 2.指定位置 onLayout(boolean,int,int,int,int)
* 3.绘制内容 onDraw(canvas)
*/
/**
* 当系统测量当前控件尺寸时调用该方法
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//告诉系统我有多大 单位:像素
setMeasuredDimension(200, 150);
}
/**
* 当系统为我们指定好位置后,调用该方法
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right,int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
/**
* 绘制内容时调用该方法
* @param canvas 画布
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.BLUE);
canvas.drawCircle(100, 75, 50, paint);
}
}
三、声明自定义属性的基本步骤
- 先声明一个属性集合,名称一般与拥有这些属性的类同名,然后在属性集合中声明属性
- 布局文件中使用这些属性:命名空间
- 在类的构造方法中获得类型数组,并根据类型数组获得指定属性名和属性值
四、声明自定义属性模板
values文件夹下创建attrs文件:
<resources>
<!-- 声明一个属性集合,名称一般与该类类名相同 -->
<declare-styleable name="MyToggleBtn">
<!-- 声明属性,类型为引用类型 -->
<attr name="my_bg" format="reference" />
<attr name="my_btn" format="reference" />
</declare-styleable>
</resources>
布局文件:
命名空间:xmlns:ishare=”http://schemas.android.com/apk/res/com.ishare.customview”
使用属性:ishare:my_bg=”@drawable/switch_background”
注意,AndroidStudio中声明命名空间:xmlns:ishare=”http://schemas.android.com/apk/res-auto”
在构造方法中获取属性名和属性值:
//获得类型数组,参数二是属性集合对应的id
TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
//获得指定名称的属性
BitmapDrawable bgDrawable=(BitmapDrawable) ta.getDrawable(R.styleable.MyCustomView_my_bg);
BitmapDrawable btnDrawable=(BitmapDrawable) ta.getDrawable(R.styleable.MyCustomView_my_btn);
bitmapBg=bgDrawable.getBitmap();
slideBtn=btnDrawable.getBitmap();