码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-12-28 00:08:36      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:log   onmeasure   特殊   err   自带   match   markdown   pre   自定义 view   

自定义 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 无效的解决方案

标签:log   onmeasure   特殊   err   自带   match   markdown   pre   自定义 view   

原文地址:https://www.cnblogs.com/codingblock/p/8067167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!