自定义View时由于wrap_content以及padding引发的问题

举个例子,当我们继承View来实现一个自定义view时,重写onDraw方法,画一个圆,canvas.drawCircle(width / 2, height / 2, radius, mPaint);当我们在布局中使用时,对其加上padding属性:padding=10;会发现padding属性根本不起作用,或者我们把width设置为wrap_content,同样会发现该属性失效了,我们也会发现width设置为wrap_content和match_parent没有任何的区别。
解决方法:
1、针对wrap_content,只需要在onMeasure方法中指定默认宽高即可,

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
 {   
 super.onMeasure(widthMeasureSpec, heightMeasureSpec);    
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);   
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);    
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);   
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);    
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode ==
MeasureSpec.AT_MOST)        
setMeasuredDimension(100, 100);    
else if (widthSpecMode == MeasureSpec.AT_MOST)        setMeasuredDimension(100, heightSpecSize);    
else if (heightSpecMode == MeasureSpec.AT_MOST)        setMeasuredDimension(widthSpecSize, 100);
}

2、padding问题:在onDraw方法中对其进行修改;

protected void onDraw(Canvas canvas) 
{    
super.onDraw(canvas);    
int paddingLeft = getPaddingLeft();    
int paddingRight = getPaddingRight();   
int paddingTop = getPaddingTop();    
int paddingBottom = getPaddingBottom();    
int width = getWidth() - paddingLeft - paddingRight;    
int height = getHeight() - paddingTop - paddingBottom;    
int radius = 50;    
canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容