zoukankan      html  css  js  c++  java
  • Android查缺补漏(View篇)--自定义 View 中 wrap_content 无效的解决方案

    自定义 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);
        }
    }
    
  • 相关阅读:
    域运算符::
    类和结构体类型的异同
    4 链表组件(817)
    2 旋转链表(61)
    1、重排链表(力扣143)
    子字符串排序的关键代码
    C语言四舍五入
    约分
    python学习第八天
    python学习第七天
  • 原文地址:https://www.cnblogs.com/codingblock/p/8067167.html
Copyright © 2011-2022 走看看