//1、创建类继承View 或View的子类。
public class MyView extends View {
//2、创建构造方法
public MyView(Context context) {
super(context);
// 在代码中new 对象时调用此方法
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
// 在XML布局文件中声明此View,创建对象时,由系统自动调用
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 与方法2用法一样,只是多了一个参数:默认样式
}
}
//3.自定义属性 //1.你需要在values目录下面新建一个名为attrs,其实这个名字是可以任意起的,并不是说取了其他的文件名Android系统就不认识, // 不过出于规范通常把属性文件命名为attrs。 //2. 首先在attrs.xml文件中声明可用属性集的名称,然后在属性集中声明属性,有属性名:name和格式:format 。
注意:format 的常用类型有 reference 引用 color 颜色 boolean 布尔值 dimension 尺寸值 float 浮点值 integer 整型值 string 字符串 enum 布尔值
3.在布局文件中使用:在使用之前必须声名命名空间,xmlns:dreams="http://schemas.android.com/apk/res/com.finddreams.slideswitch"
说明:xmlns 是XML name space xml的命名空间的缩写;
dreams可为任意写符
http://schemas.android.com/apk/res/ 此为android固定格式,必须这样写
com.finddreams.slideswitch 此应用的包名,如manifest配置文件中package包名一致。