1、写一个类继承View或你想扩展功能的控件(比如TextView)。
public class CustomView extends View { };
2、在/res/value下创建一个attr.xml文件。
没有这个文件自定义控件照样能显示出来,但只能使用所继承的父类中包含的属性,有了这个文件可以增加自定义的命名空间,来设置自定义的属性(其中format可选值见文尾)(大家看到这里可能觉得很突兀,坚持看完,相信你会明白这里的!)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
2、CustomView中重写父类的构造方法(我一般把三个都写上)在构造方法中获取到自定义是属性的值。
public CustomView(Context context) {
super(context);
}
//xml文件解析的时候,会把标签解析成一个类,标签里的属性及属性值都传递到AttributeSet里了,所以我们要从这里把属性值获取出来,设置给画笔。
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context,attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomView);//获取定义在attr中属性的属性值,这个属性值是在,把控件设置到界面上时所使用的layout中设置的
int color = array.getColor(R.styleable.CustomView_textColor, Color.RED);//第二个参数为默认值
float size = array.getDimension(R.styleable.CustomView_textSize, 10);
paint = new Paint();
paint.setColor(color);
paint.setTextSize(size);
array.recycle();//必须有!!清空原array,防止以后出现原来设置的属性。
}
4、重写onDraw()方法。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("我是被画出来的", 10, 100, paint);//第二个和第三个参数为坐标的X轴Y轴
}
5、新建一个Activity(此处不再给出),在其使用的布局文件中添加自定义控件,并且可以引入自定义的命名空间,使用attr中定义的属性。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dinglin="http://schemas.android.com/apk/res/cn.itheima.customview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 使用自定义控件要用包名+类名的形式,其中命名控件dl中可以使用在attr.xml中定义的属性 -->
<cn.itheima.customview.CustomView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
dl:textColor="#ff00ff00"
dl:textSize="25dip" >
</cn.itheima.customview.CustomView>
</LinearLayout>