自定义控件

本文详细解析了自定义View与ViewGroup的基础原理,包括继承View与ViewGroup的示例,以及View的绘制流程,从measure、layout到draw的过程。深入探讨了MeasureSpec在测量过程中的应用,以及onMeasure与onLayout方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 继承ViewGroup
例如:ViewGroup、LinearLayout、FrameLayout、RelativeLayout等。
  2. 继承View
例如:View、TextView、ImageView、Button等。

自定义控件基本绘制原理:
View的绘制基本上由measure()、layout()、draw()这个三个函数完成

1.)测量-Measure过程是计算视图大小,View measure过程相关方法主要有三个:

measure调用onMeasure,onMeasure测量宽度、高度
MeasureSpec.getSize(widthMeasureSpec);// 获取宽度值
MeasureSpec.getMode(widthMeasureSpec);// 获取宽度模式
MeasureSpec.getMode(heightMeasureSpec);// 获取高度模式
MeasureSpec.getSize(heightMeasureSpec);// 获取高度值
// 按照最新的高度和宽度设置空间宽高
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
public final void measure(int widthMeasureSpec, int heightMeasureSpec)
然后调用setMeasureDimension保存测量结果
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

布局-Layout过程用于设置视图在屏幕中显示的位置,View layout过程相关方法主要要三个:
public void layout(int l, int t, int r, int b)
protected boolean setFrame(int left, int top, int right, int bottom)
protected void onLayout(boolean changed, int left, int top, int right, int bottom)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值