第一步:建立一个MyCustomView继承View,实现构造方法
/**
* Created by chenshouyin on 17/3/9.
*/
public class MyCustomView extends View {
//1.此处应该继承View
//2.此处用this依次调用第二个第三个构造方法
public MyCustomView(Context context) {
//super(context);
this(context, null);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
//super(context, attrs);
this(context, attrs, 0);
}
public MyCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//3.此处得到attrs.xml里面,我们的自定义的样式属性 Attribute属性的意思,AttributeSet那么就是xml中的属性设置的意思
}
}
第二步:在res资源文件夹新建atts.xml文件设置自定义View需要用到的属性
`
**第三步:布局文件中引用自定义属性并且使用自定义属性**
Paste_Image.png
小技巧:主要输入custom:编译器会自动给我们导入
zhu
网上导入是这样子的
xmlns:custom="http://schemas.android.com/apk/res/hxing.com.mycustomtextview.MyCustomTextView
可能AS版本的问题,我这里会提示用
xmlns:custom="http://schemas.android.com/apk/res-auto"
csy.jpg
好了,到此,我们在布局文件也已经引入了自定义View,那么运行程序,是不是可以看到TextView了呢?别急,我们还没把View画出来呢。
第四步:设置画笔大小,颜色,字体。
private String mTextViewString;
private int mTextViewColor;
private int mTextViewSize;
思考:为什么MyCustomView中已经设置了文字,文字颜色,文字大小,还要设置画笔大小,颜色,字体呢?
custom:titleColor="#d41e1e"
custom:titleSize="16sp"