Android 自定义视图

时间:2023-02-09 21:09:08

Android自定义视图很简单,新建类继承于android.view.View类,实现onDraw()函数,然后直接在layout里面使用即可

需要注意的几点:自定义视图构造函数要实现带有AttributeSet参数那个,要不一直报错.

上代码:

public class MyView extends View {
private Paint myPaint;
private DisplayMetrics dm;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
myPaint=new Paint();
myPaint.setColor(Color.RED);
myPaint.setTextSize(30);
dm=new DisplayMetrics();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(dm);

myPaint.setStyle(Style.FILL);
canvas.drawLine(20, 20, dm.widthPixels-40, 20, myPaint);//4个参数分别是起始x、y坐标,终点x、y坐标
canvas.drawLine(20, 220, dm.widthPixels-40, 220, myPaint);
canvas.drawLine(20, 420, dm.widthPixels-40, 420, myPaint);
canvas.drawLine((dm.widthPixels-40)/2, 20, (dm.widthPixels-40)/2, 420, myPaint);

myPaint.setColor(Color.GREEN);
canvas.drawRect(20, 20, 250, 100, myPaint);//4个参数分别是左、上、右、下的坐标值
canvas.drawCircle(250, 300, 100, myPaint);//画圆周,3个参数分别是圆心X轴坐标,Y轴坐标,以及圆的半径
}
}

在layout引用:<com.findsoft.customerview.view.MyView  
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>