//xml中导入工程包一、重写的方法1 public MyView(Context context, AttributeSet attrs, int defStyleAttr)
2.public MyView(Context context, AttributeSet attrs)
protected void onDraw(Canvas canvas)创建画笔,,,设置
xml代码:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xxx="http://schemas.android.com/apk/res/com.example.viewzidingyi"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<com.example.viewzidingyi.MyView
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xxx:color="#f00"
xxx:size="30sp"
></com.example.viewzidingyi.MyView>
</RelativeLayout>
public class MyView extends View {
// 怎么画, 由Paint处理
private Paint paint;
private Context context;
private static final String mname = "我是自定义view";
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
// 实现两个方法,
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TypedArray a = context.obtainStyledAttributes(attrs,
// R.styleable.customeAttrs);
// float size = a.getDimension(R.styleable.customeAttrs_size, 20);
// int color = a.getColor(R.styleable.customeAttrs_color, 0xff000000);
//
}
public MyView(Context context) {
super(context);
}
// 画什么, 由Canvas处理 canvas 即为白纸
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// 实例化一个画笔
paint = new Paint();
// 设置画笔的颜色
paint.setColor(Color.RED);
// 大小
paint.setTextSize(50);
// 填充
paint.setStyle(Style.FILL);
// 画一个矩形
canvas.drawRect(50, 50, 200, 200, paint);
paint.setColor(Color.BLUE);
// 绘制文字
canvas.drawText(mname, 20, 20, paint);
}
}