Android查缺补漏(View篇)--自定义 View 中 wrap_content 无效的解决方案

2023-07-12,,

自定义 View 中 wrap_content 无效的解决方案

做过自定义 View 的童鞋都会发现,直接继承 View 的自定义控件需要重写 onMeasure() 方法,并设置 wrap_content 时的自身大小,否则在布局文件中对自定义控件在设置大小时,wrap_content 将等同于 match_parent。

其实在 Android 中自带的控件中,也都对 onMeasure() 方法进行了重写,对于 wrap_content 等情况做了特殊处理,在 wrap_content 时给出了默认的宽、高。所以对于这个问题的处理我们也就有了一定的思路,在 onMeasure() 中对于 wrap_content 情况给出合适的宽、高即可,代码如下:

@Override
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 heithtSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, 200);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(200, heithtSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpecSize, 200);
}
}

Android查缺补漏(View篇)--自定义 View 中 wrap_content 无效的解决方案的相关教程结束。

《Android查缺补漏(View篇)--自定义 View 中 wrap_content 无效的解决方案.doc》

下载本文的Word格式文档,以方便收藏与打印。