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"/>

更多相关文章

  1. Android activity 参数传递
  2. Android的intent之间复杂参数的传递
  3. android 使用intent传递参数实现乘法计算
  4. Android中的DrawRect()参数解析
  5. Android参数设置: Preference
  6. Android cmd 命令常用参数详解
  7. 自定义视图中使用自定义变量
  8. Android GPS获取当前经纬度坐标

随机推荐

  1. [Android] 来电归属地查询的实现思路
  2. A first hand look at building an Andro
  3. TableLayout
  4. android sim卡 TelephonyManager类:Androi
  5. Android(安卓)开发 — 开机自启动
  6. 2010.10.30———Android(安卓)03
  7. Android官方入门文档[14]停止和重新启动
  8. android NDK 开发环境配置
  9. android emulator 配置_
  10. 安卓编程小tips