如何在Android应用中实现自定义View-创新互联

本篇文章为大家展示了如何在Android应用中实现自定义View,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联公司是一家专注于网站设计、网站建设与策划设计,牟定网站建设哪家好?创新互联公司做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:牟定等地区。牟定做网站价格咨询:18982081108

Android自定义view的种类

自定义view大概可以分为四个大类,主要是通过实现方式来区分

      1.自绘控件,继承view,重写onDraw方法,在其中进行绘制,需要自己适配边距等等

      2.继承ViewGroup派生的特殊Layout,主要用于实现自定义布局,也需要自己适配边距等

      3.继承特定的View(如TextView等),不用自己适配支持wrap_conten,match_parent,可以给其加入新的功能

      4.继承特定的ViewGroup,例如linearlayout,多用于多个控件的组合view,也不用自己去做适配

自绘控件

这种自定义view是最复杂的一种,因为既要适配wrap_conten,match_parent又要通过条件判断来在屏幕上绘制不同的内容,主要就是重写onDraw方法

以下是一个简单的onDraw重写代码

@Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
 
  final int paddingLeft = getPaddingLeft();
  final int paddingRight = getPaddingRight();
  final int paddingTop = getPaddingTop();
  final int paddingBottom = getPaddingBottom();
 
  //get the view's width and height and decide the radiu
  int width = getWidth() - paddingLeft - paddingRight;
  int height = getHeight() - paddingTop - paddingBottom;
  radiu = Math.min(width , height) / 2 - boundWidth - progressWidth;
 
  //setup the paint
  paint.setStyle(Paint.Style.STROKE);
  paint.setStrokeWidth(boundWidth);
  paint.setColor(Color.BLACK);
 
  //draw the inner circle
  int centerX = paddingLeft + getWidth()/2;
  int centerY = paddingTop + getHeight() / 2;
  canvas.drawCircle(centerX,centerY, radiu, paint);
  
 
  float totalRadiu = radiu +boundWidth +progressWidth/2;
 
  //draw the circlr pic
  if (drawable != null&&bitmap == null) {
   image = ((BitmapDrawable) drawable).getBitmap();
 
   bitmap = Bitmap.createBitmap((int)(2*totalRadiu),(int)(2*totalRadiu), Bitmap.Config.ARGB_8888);
   Canvas bitmapCanvas = new Canvas(bitmap);
 
   Paint bitmapPaint = new Paint();
   bitmapPaint.setAntiAlias(true);
 
   bitmapCanvas.drawCircle(totalRadiu, totalRadiu, radiu, bitmapPaint);
 
   bitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
   bitmapCanvas.drawBitmap(image,null,new RectF(0,0,2*totalRadiu,2*totalRadiu) , bitmapPaint);
 
 
  }
  Rect rect = new Rect((int)(centerX -totalRadiu),(int)(centerY-totalRadiu),(int)(centerX+totalRadiu),(int)(centerY+ totalRadiu));
  canvas.save();
  if(isRotate)
  canvas.rotate(rotateDegree,centerX,centerY);
  canvas.drawBitmap(bitmap,null ,rect, paint);
 
  canvas.restore();
  //set paint for arc
  paint.setStrokeWidth(progressWidth);
  paint.setStrokeCap(Paint.Cap.ROUND);
 
  //prepare for draw arc
  RectF oval = new RectF();
  oval.left = centerX -totalRadiu ;
  oval.top =centerY- totalRadiu ;
  oval.right = centerX + totalRadiu;
  oval.bottom = centerY+ totalRadiu;
  paint.setColor(progressBackColor);
 
  //draw background arc
  canvas.drawArc(oval, arcStar, arcEnd, false, paint);
 
  //draw progress arc
  paint.setColor(progressColor);
  canvas.drawArc(oval, arcStar, progress, false, paint);
 }

本文名称:如何在Android应用中实现自定义View-创新互联
文章链接:http://azwzsj.com/article/jgijo.html