zoukankan      html  css  js  c++  java
  • Android的onMeasure方法

    Android开发中,当Android原生控件不能满足我们的需求的时候,就需要自定义View。View在屏幕上绘制出来先要经过measure(计算)和layout(布局)。

    什么时候调用onMeasure方法?
    当子View的父控件要放置该View的时候,父控件会传递两个参数给View——widthMeasureSpec和heightMeasureSpec。这两个参数是View可以获取的宽高尺寸和模式值混合的int数据。可以通过int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size = MeasureSpec.getSize(widthMeasureSpec)得到尺寸。

    mode共有三种情况,取值分别为

    MeasureSpec.UNSPECIFIED,MeasureSpec.EXACTLY,MeasureSpec.AT_MOST。


    MeasureSpec.EXACTLY是精确尺寸,当我们将控件的layout_width或layout_height指定为具体数值时如
    andorid:layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸。

    MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸。

    MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式。

    可以调用setMeasuredDimenson方法,将View的高度和宽度传入,设置子View实际的大小,告诉父控件需要多大的空间放置子View。

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     
        int measuredHeight = measureChild(heightMeasureSpec);
     
        int measuredWidth = measureChild(widthMeasureSpec);
     
        setMeasuredDimension(measuredHeight, measuredWidth);
     
    }
     private int measureChild(int measureSpec) {
     
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
     
        int result = 500;
        if (specMode == MeasureSpec.AT_MOST) { 
            result = specSize;
        } else if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        }
        return result;
    }
  • 相关阅读:
    crontab 定时任务设置
    kafka如何保证消息得顺序性
    Spark Streaming和Kafka整合是如何保证数据零丢失
    docker学习之路(安装、使用)
    linux根文件系统 /etc/resolv.conf 文件详解
    Navicat Premium 12连接MySQL数据库出现Authentication plugin 'caching_sha2_password' cannot be loaded的解决方案
    window10 安装Mysql 8.0.17以及忘记密码重置密码
    ubantu安装mysql (解决配置密码问题)
    Navicat Premium 12 connection is being used以及查询sql文件保存位置
    离线安装PM2
  • 原文地址:https://www.cnblogs.com/lchd/p/3593861.html
Copyright © 2011-2022 走看看