android 自定义view 详解

📅 发布时间:2026/8/16 1:23:25
android 自定义view 详解 Android 自定义 View 详解自定义 View 是 Android 开发的核心技能之一本文从原理到实践系统梳理自定义 View 的完整知识体系。一、自定义 View 的三种方式方式适用场景核心工作继承现有控件如TextView、ImageView在已有控件基础上扩展功能复用绘制逻辑重写关键方法继承View完全自定义绘制内容如饼图、进度条重写onMeasureonDraw继承ViewGroup自定义布局管理器如流式布局、瀑布流重写onMeasureonLayout二、核心生命周期方法1. 构造方法Constructorkotlinclass CustomView JvmOverloads constructor( context: Context, attrs: AttributeSet? null, defStyleAttr: Int 0 ) : View(context, attrs, defStyleAttr) { init { // 读取自定义属性 val typedArray context.obtainStyledAttributes(attrs, R.styleable.CustomView) val color typedArray.getColor(R.styleable.CustomView_circleColor, Color.RED) typedArray.recycle() } }三个构造方法的区别View(Context)代码中直接 newView(Context, AttributeSet)XML 中使用View(Context, AttributeSet, Int)XML 中使用 指定 style2. onMeasure —— 测量尺寸kotlinoverride fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val widthMode MeasureSpec.getMode(widthMeasureSpec) val widthSize MeasureSpec.getSize(widthMeasureSpec) // 三种测量模式 when (widthMode) { MeasureSpec.EXACTLY - { /* match_parent 或具体数值 */ } MeasureSpec.AT_MOST - { /* wrap_content */ } MeasureSpec.UNSPECIFIED - { /* 父布局不限制如 ScrollView 内 */ } } // 设置最终测量结果 setMeasuredDimension(resolveSize(desiredWidth, widthMeasureSpec), resolveSize(desiredHeight, heightMeasureSpec)) }测量模式速查Mode触发条件处理方式EXACTLYmatch_parent/ 具体 dp直接使用给定尺寸AT_MOSTwrap_content计算内容所需尺寸不超过上限UNSPECIFIED父布局不限制按内容实际需要设置3. onSizeChanged —— 尺寸变化kotlinoverride fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // 初始化与尺寸相关的对象如 Rect、Path、Shader centerX w / 2f centerY h / 2f radius min(w, h) / 2f - padding }4. onDraw —— 绘制内容核心kotlinoverride fun onDraw(canvas: Canvas) { super.onDraw(canvas) // 1. 绘制背景系统已处理通常不需要手动调用 // 2. 绘制内容 canvas.drawCircle(centerX, centerY, radius, paint) canvas.drawRect(rect, paint) canvas.drawText(Hello, x, y, textPaint) // 3. 使用 Path 绘制复杂图形 val path Path().apply { moveTo(100f, 100f) lineTo(200f, 200f) quadTo(300f, 100f, 400f, 200f) // 二次贝塞尔曲线 close() } canvas.drawPath(path, paint) }Canvas 常用绘制 APIdrawCircle() drawRect() drawOval() drawArc() drawLine() drawPoint() drawText() drawBitmap() drawPath()5. onLayout仅 ViewGroupkotlinoverride fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { for (i in 0 until childCount) { val child getChildAt(i) // 计算子 View 的位置 child.layout(left, top, right, bottom) } }三、Paint 详解 —— 画笔配置kotlinval paint Paint(Paint.ANTI_ALIAS_FLAG).apply { color Color.RED // 颜色 strokeWidth 8f // 描边宽度 style Paint.Style.STROKE // FILL / STROKE / FILL_AND_STROKE strokeCap Paint.Cap.ROUND // 线帽BUTT / ROUND / SQUARE strokeJoin Paint.Join.ROUND // 连接处MITER / ROUND / BEVEL isAntiAlias true // 抗锯齿 isDither true // 防抖动颜色过渡更平滑 // 高级效果 shader LinearGradient(...) // 渐变 maskFilter BlurMaskFilter(...) // 模糊效果 pathEffect DashPathEffect(...) // 虚线效果 }四、完整示例圆形进度条1. 自定义属性res/values/attrs.xmlxml?xml version1.0 encodingutf-8? resources declare-styleable nameCircleProgressView attr nameprogressColor formatcolor/ attr namebgColor formatcolor/ attr namestrokeWidth formatdimension/ attr namemaxProgress formatinteger/ attr namecurrentProgress formatinteger/ /declare-styleable /resources2. 完整 View 代码kotlinclass CircleProgressView JvmOverloads constructor( context: Context, attrs: AttributeSet? null, defStyleAttr: Int 0 ) : View(context, attrs, defStyleAttr) { private var progressColor Color.parseColor(#2196F3) private var bgColor Color.parseColor(#E0E0E0) private var strokeWidth 20f private var maxProgress 100 private var currentProgress 0 private val bgPaint Paint(Paint.ANTI_ALIAS_FLAG) private val progressPaint Paint(Paint.ANTI_ALIAS_FLAG) private val rectF RectF() init { context.obtainStyledAttributes(attrs, R.styleable.CircleProgressView).apply { progressColor getColor(R.styleable.CircleProgressView_progressColor, progressColor) bgColor getColor(R.styleable.CircleProgressView_bgColor, bgColor) strokeWidth getDimension(R.styleable.CircleProgressView_strokeWidth, strokeWidth) maxProgress getInt(R.styleable.CircleProgressView_maxProgress, maxProgress) currentProgress getInt(R.styleable.CircleProgressView_currentProgress, currentProgress) recycle() } bgPaint.apply { color bgColor this.strokeWidth thisCircleProgressView.strokeWidth style Paint.Style.STROKE strokeCap Paint.Cap.ROUND } progressPaint.apply { color progressColor this.strokeWidth thisCircleProgressView.strokeWidth style Paint.Style.STROKE strokeCap Paint.Cap.ROUND } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val size resolveSize(200.dpToPx(), widthMeasureSpec) setMeasuredDimension(size, size) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) val padding strokeWidth / 2 rectF.set(padding, padding, w - padding, h - padding) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // 绘制背景圆环 canvas.drawArc(rectF, 0f, 360f, false, bgPaint) // 绘制进度圆弧 val sweepAngle 360f * currentProgress / maxProgress canvas.drawArc(rectF, -90f, sweepAngle, false, progressPaint) // 绘制进度文字 val text $currentProgress% val textPaint Paint(Paint.ANTI_ALIAS_FLAG).apply { color progressColor textSize width / 4f textAlign Paint.Align.CENTER } val baseline height / 2f - (textPaint.descent() textPaint.ascent()) / 2 canvas.drawText(text, width / 2f, baseline, textPaint) } fun setProgress(progress: Int) { currentProgress progress.coerceIn(0, maxProgress) invalidate() // 请求重绘 } private fun Int.dpToPx(): Int (this * resources.displayMetrics.density).toInt() }3. XML 中使用xmlcom.example.CircleProgressView android:layout_width120dp android:layout_height120dp app:progressColorcolor/purple_500 app:bgColor#F5F5F5 app:strokeWidth12dp app:maxProgress100 app:currentProgress75/五、触摸事件处理kotlinoverride fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN - { parent.requestDisallowInterceptTouchEvent(true) // 处理按下逻辑 return true // 消费事件 } MotionEvent.ACTION_MOVE - { // 处理滑动逻辑 } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL - { parent.requestDisallowInterceptTouchEvent(false) // 处理抬起逻辑 } } return super.onTouchEvent(event) }事件分发要点dispatchTouchEvent→ 事件入口onInterceptTouchEvent仅 ViewGroup→ 是否拦截onTouchEvent→ 实际处理返回true表示消费事件不再向上传递六、动画与属性更新kotlin// 方式1属性动画 ValueAnimator.ofInt(0, 100).apply { duration 2000 interpolator DecelerateInterpolator() addUpdateListener { animator - setProgress(animator.animatedValue as Int) } start() } // 方式2配合 ObjectAnimator var progress: Int 0 set(value) { field value invalidate() } ObjectAnimator.ofInt(this, progress, 0, 100).apply { duration 1500 start() }七、性能优化建议优化项说明避免在onDraw中创建对象所有 Paint、Path、Rect 应在init或onSizeChanged中初始化使用invalidate(Rect)局部重绘只重绘变化区域减少绘制工作量开启硬件加速android:hardwareAcceleratedtrue但注意部分 API 不支持减少过度绘制避免多层重叠绘制使用clipRect裁剪复杂图形使用 Bitmap 缓存静态内容先绘制到 Bitmap后续直接drawBitmap使用requestLayout()谨慎会触发完整测量-布局-绘制流程开销大八、常见问题排查问题原因解决方案自定义 View 不显示未重写onMeasure且父布局为wrap_content重写onMeasure设置默认尺寸wrap_content无效未处理AT_MOST模式在onMeasure中处理文字绘制位置偏移未计算 baseline使用Paint.FontMetrics计算触摸事件不响应onTouchEvent返回 false返回 true 消费事件动画卡顿主线程阻塞或过度绘制使用 Choreographer减少绘制层级九、进阶方向自定义 Drawable实现Drawable接口可复用于多个 ViewRenderThread / RenderNodeAndroid 10 的硬件渲染优化Compose 自定义使用CanvasModifier 或LayoutComposableSVG Path 动画AnimatedVectorDrawable实现复杂路径动画