主动测量View的宽高

熟知UI显示流程的同学可能都知道,View要获取到尺寸,必须经过测量才能拿到,而测量则是UI显示流程的一个环节,所以按照成正常情况想要获取到View的尺寸,就需要至少等到View显示过程中的测量环节结束才能拿到。但是在开发过程中,可能有一些小众场景,为了显示效果,需要在View显示流程触发之前,对未固定尺寸的View根据内容获取其宽高,进而做其他显示上处理,如果有这样需求的同学,那么通过本篇你将学会如何在View显示流程触发之前获取View的宽高。

代码我已经封装为一个函数,可以拿来直接用,很简单,我就不再过多赘述。

Kotlin实现代码:

Kotlin 复制代码
   fun viewMeasure(view:View):Size{
        var widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED)
        var heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED)

        // 测量View
        view.measure(widthMeasureSpec, heightMeasureSpec)

         // 获取测量后的宽和高
        var measuredWidth = view.getMeasuredWidth()
        var measuredHeight = view.getMeasuredHeight()

        // 输出宽和高
        Log.d("TextViewMeasure", "Width: $measuredWidth, Height: $measuredHeight")
        return Size(measuredWidth,measuredHeight)
    }

Java实现代码:

java 复制代码
    public Size viewMeasure(View view){
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);

        // 测量View
        view.measure(widthMeasureSpec, heightMeasureSpec);

        // 获取测量后的宽和高
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();

        // 输出宽和高
        Log.d("TextViewMeasure", "Width: "+measuredWidth+", Height: "+measuredHeight);
        return new Size(measuredWidth,measuredHeight);
    }
相关推荐
夜雪一千13 分钟前
如何在MySQL中实现字段级加密
android·数据库·mysql
夜雪一千15 分钟前
MySQL 如何存储经纬度坐标:选型、建表、空间查询实战
android·mysql·adb
JMchen31 分钟前
集成第三方 C/C++ 库到 Android NDK 项目:OpenCV 与 FFmpeg 实战指南
android·opencv·cmake
有毒的教程2 小时前
Dev-C++ 使用扩展库两种方式:DevPak一键安装 / 手动配置(重点)
android·c++·adb
mmsx3 小时前
Android 测绘数值基础:测量单位系统与七四参数、高程拟合
android
郑州光合科技余经理3 小时前
出海外卖平台:支付对接为什么要和下单收款分开
android·java·开发语言·前端·后端·php·ai编程
夜雪一千3 小时前
MySQL 如何提高查询速度:从索引、SQL、表结构到实战调优
android·sql·mysql
终端安全笔记3 小时前
配置锁状态那一栏查的是什么:报告里几项各自指向什么风险
android·前端·安全·ios
恋猫de小郭3 小时前
Kotlin Toolchain 0.13,JetBrains 推荐 KMP 都切换到到全新工具链
android·前端·flutter
安卓机器4 小时前
rom定制系列------小米8 安卓16线刷原生固件 体验新版本
android·小米8安卓16